如何在preg_replace()函数中使用substr()函数?

fis*_*ood 5 php regex html-parsing

这就是我到目前为止所做的,但无论我尝试什么,我album-content都不会被截断substr().

$gallery = preg_replace('/(<div class="album-content">)(.*?)(<\/div>)/e', "'$1' . substr(\"$2\", 0, 50) . '$3'", $gallery);
Run Code Online (Sandbox Code Playgroud)

更新:

原来我的班级名称不正确,我的正则表达式似乎确实有效.我只需要执行另一个str_replace()来取消输出.

$gallery = preg_replace('/(<div class="album-desc">)(.*?)(<\/div>)/e', "'$1' . substr(\"$2\", 0, 50) . '$3'", $gallery);
$gallery = str_replace('\"album-desc\"', '"album-desc"', $gallery);
Run Code Online (Sandbox Code Playgroud)

修改前的输出:

<a href="..." class="album">
    <div class="album-content"><p class="album-title">Album 1</p>
        <div class="album-desc"><p>This will be truncated by substr().</p></div>
    </div>
    <img src="..." />
</a>
Run Code Online (Sandbox Code Playgroud)

谢谢大家,反正!

Dav*_*ris 4

使用preg_replace_callback()

$replace = preg_replace_callback('/(asd)f/i', function($matches) {
    $matches[1] = substr($matches[1], 0, 2);

    return $matches[1];
}, 'asdf');
Run Code Online (Sandbox Code Playgroud)

完整文档