gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:51 24 4
gpt4 key购买 nike

这是我目前所拥有的,但无论我尝试什么,我的 album-content 都不会被 substr() 截断。

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

更新:

原来我的类名不正确,我的正则表达式似乎确实有效。我只需要执行另一个 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);

修改前的输出:

<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>

无论如何,谢谢大家!

最佳答案

使用preg_replace_callback()

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

return $matches[1];
}, 'asdf');

Full documentation

关于php - 如何在 preg_replace() 函数中使用 substr() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14324996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com