2 回答
TA贡献1847条经验 获得超7个赞
使用 regexp php 函数preg_replace,您可以将搜索模式和替换传递添加为两个数组:
$string = preg_replace([
'/ title="[^"]+"/',
'/ desc="[^"]+"/',
], [
sprintf(' title="%s"', 'replacement'),
sprintf(' desc="%s"', 'replacement'),
], $string);
// NOTE: Space was added in front of title= and desc=
// EXAMPLE: If you do not have a space, then it will replace the text in the quotes for title="text-will-get-replaced" as well as something similar like enable_title="text-will-get-replaced-as-well". Adding the space will only match title= but not enable_title=
TA贡献1824条经验 获得超5个赞
出于兴趣和比较的目的,我将我的原始功能作为“如何不这样做”的示例发布。
我建议使用 preg_replace 而不是 Pavel Musil 的答案:
<?php
$string = '[some_block title="any text" aaa="something" desc="anytext" bbb="something else"]';
$new_string = replaceSpecial('title=', '"', 'my new text', $string);
echo $new_string; // will output: [some_block title="my new text" aaa="something" desc="anytext" bbb="something else"]
function replaceSpecial($needle, $text_wrapper, $new_text, $haystack) {
$new_string = $haystack;
$needle_arr = explode($needle, $haystack, 2);
if (count($needle_arr) > 1) {
$wrapper_arr = explode($text_wrapper, $needle_arr[1], 3);
$needle_arr[1] = $wrapper_arr[0].$needle.'"'.$new_text.'"'.$wrapper_arr[2];
$new_string = $needle_arr[0].$needle_arr[1];
}
return $new_string;
}
?>
- 2 回答
- 0 关注
- 106 浏览
添加回答
举报