【问题标题】:Replace specific parts of string in PHP替换PHP中字符串的特定部分
【发布时间】:2020-04-18 19:03:29
【问题描述】:

我有一个如下所示的字符串:

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

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

【问题讨论】:

  • 你熟悉正则表达式吗?
  • @ADyson 我对正则表达式很熟悉,指出它们完全让我感到困惑,我不太了解它们:(

标签: php


【解决方案1】:

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

【讨论】:

  • 虽然代码很简单,而且你已经很好地分隔了它,但它仍然应该有一些描述。比如什么是正则表达式以及在这种情况下它是如何工作的
  • 好的,我以后会做更多的描述。
  • @PavelMusil 好吧,我不太明白,但它有效!谢谢
  • 所以我注意到的一个问题是代码将替换 title= 引号中的文本,但也替换 any_title= 的文本。我已经编辑了代码并在 title 和 desc 前面放置了一个空格它只会替换所需的部分。
  • 嗨,如果空间缺失,空间'_title="[^"]+"' 有问题。所以,尝试使用不带空格的正则表达式模式'title="[^"]+"'
【解决方案2】:

出于兴趣和比较的目的,我将我的原始函数发布为“如何做到这一点”的示例。

我建议使用 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;
}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2013-09-22
    相关资源
    最近更新 更多