-1

我正在努力理解 php 的功能striposstr_replace工作方式。

我有一段文字,例如:{% if group.newt !== "" %} XYZ's {% else %} ABC's {% endif %}

我想用Go to this link www.google.com.

我搜索正文:

if(stripos($entity->getBodyOfText(), $strTFind) !== false) {preg_match("{% if group.newt !== "" %} XYZ's {% else %} ABC's {% endif %}", $strToReplace)};

或者

$str_replace($strToFind, $strToReplace, $entity->getBodyOfText());

我得到的结果是没有找到或替换文本!我不懂为什么。有人可以为我解释一下吗?

编辑:

正文是一个包含大量图像、文本和树枝代码的电子邮件模板。在一组特定的电子邮件模板中,我需要用一行文本查找并替换整个树枝代码块(无论该文本是什么)。我遇到的问题是,当我使用str_replaceor在电子邮件模板中搜索代码块时preg_replace,这些函数找不到或替换我要查找和替换的块。

所以我的输出是一样的(什么都没有找到,什么都没有改变)。

例如:

    `here would be an image 

    now starts a heading,

      some more text with {{ twig.variable }} and then more text.
    more

    text, lots more text some {% twig.fucntions %}blah{% ending %} and 
then here is the block 
I want to find and replace: {% replace this whole thing including the brackets and percentage signs %}keep replacing
{% else %}
replace that else (everything including the brackets and percentage signs)and
{% this too %}.

    some more ending text.

    image,

    the end`

我希望这会有所帮助!

4

2 回答 2

0

使用 str_replace...

str_replace("Pattern to search",$stringToSearch,"Replacement text");

所以在实践中:

$string = "{% if group.newt !== '' %} XYZ's {% else %} ABC's {% endif %}";

$newString = str_replace("{% if group.newt !== '' %} XYZ's {% else %} ABC's {% endif %}",$string,"Go to this link www.google.com");

echo $newString;

仅供参考,您需要链接该链接才能使其成为实际链接。还将比较中的 "" 固定为 '' 以适应用 " " 封装的 PHP;

在 PhpFiddle.com 中测试

如果您打算使用您的功能

$entity->getBodyOfText(); 

用它替换 $string,或者分配

$string = $entity->getBodyOfText();
于 2017-05-11T13:28:14.823 回答
0

使用非正则表达式解决方案要求您确切知道要替换的子字符串——我假设您知道子字符串。需要注意的是,如果子字符串有可能多次出现并且您只想要一个替换,那么str_replace()替换所有找到的子字符串将使您失败。如果子字符串在字符串中是唯一的,或者您想替换所有重复的子字符串,那么一切都会按预期工作。

代码(演示):

$find='{% replace this whole thing including the brackets and percentage signs %}keep replacing
{% else %}
replace that else (everything including the brackets and percentage signs)and
{% this too %}.';
$replace='LINK';

$text=str_replace($find,$replace,$text);
echo "$text";

输出:

here would be an image 

    now starts a heading,

      some more text with {{ twig.variable }} and then more text.
    more

    text, lots more text some {% twig.fucntions %}blah{% ending %} and 
then here is the block 
I want to find and replace: LINK

    some more ending text.

    image,

    the end

如果您需要更好的定制解决方案,请说明此方法如何使您失败,我会对其进行调整。

于 2017-05-12T03:08:51.097 回答