在 PHP 中替换字符串的特定部分

我有一个看起来像这样的字符串:

$string = '[some_block title="any text" aaa="something" desc="anytext" bbb="something else"]';

我需要替换 title= 和 desc= 引号之间的文本

title 和 desc 的顺序可以改变,这意味着 desc 可以在 title 之前,或者也可以有其他的东西,比如 aaa= 或 bbb= before/inbetween/after。

我不能使用 str_replace 因为我不知道引号之间会出现什么文本。

我在想一个可能的解决方案是我可以在 title= 上展开,然后在双引号上展开,然后将它与新文本拼凑起来,并重复 desc=

只是想知道是否有更好的解决方案,我不知道做这样的事情?


慕桂英546537
浏览 108回答 2
2回答

aluckdog

使用 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=

沧海一幻觉

出于兴趣和比较的目的,我将我的原始功能作为“如何不这样做”的示例发布。我建议使用 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) {&nbsp; &nbsp; $new_string = $haystack;&nbsp; &nbsp; $needle_arr = explode($needle, $haystack, 2);&nbsp; &nbsp; if (count($needle_arr) > 1) {&nbsp; &nbsp; &nbsp; &nbsp; $wrapper_arr = explode($text_wrapper, $needle_arr[1], 3);&nbsp; &nbsp; &nbsp; &nbsp; $needle_arr[1] = $wrapper_arr[0].$needle.'"'.$new_text.'"'.$wrapper_arr[2];&nbsp; &nbsp; &nbsp; &nbsp; $new_string = $needle_arr[0].$needle_arr[1];&nbsp; &nbsp; }return $new_string;}?>
打开App,查看更多内容
随时随地看视频慕课网APP