在PHP中的字符串中最后一次出现特定字符之前插入

时间:2014-08-07 14:31:54

标签: php

我想在字符串中最后一次出现特定字符之前插入一些东西。

在下面的案例中,将<p>的最后一次出现替换为Hello <p>

$tdr="<p>Previous reports stated that the Pokemon Alpha.</p><p>On the other hand, Pokemon Diamond and Pearl are reported .</p><p>On the other hand, Pokemon Diamond and Pearl are reported.</p>";

$newtdr= "<p>Previous reports stated that the Pokemon Alpha.</p><p>On the other hand, Pokemon Diamond and Pearl are reported .</p> Hello <p>On the other hand, Pokemon Diamond and Pearl are reported.</p>";

非常感谢。

3 个答案:

答案 0 :(得分:1)

一种选择是使用具有负前瞻的正则表达式:

print preg_replace("~<p>(?!.*<p>)~", "Hello $0", $tdr);

如果您更喜欢字符串函数,请尝试strrpos

 $n = strrpos($tdr, '<p>');
 print substr($tdr, 0, $n)  . ' Hello ' . substr($tdr, $n);

答案 1 :(得分:0)

$tdr="<p>Previous reports stated that the Pokemon Alpha.</p><p>On the other hand, Pokemon Diamond and Pearl are reported .</p><p>On the other hand, Pokemon Diamond and Pearl are reported.</p>";

$pos = strrpos($tdr, '<p>');

$newtdr = substr($tdr,0,$pos) . ' Hello ' . substr($tdr, $pos);

echo $newtdr;

应该对它进行排序。

如果您迫切希望将其作为替换使用以下内容:

$newtdr = substr($tdr,0,$pos) . ' Hello <p>' . substr($tdr, $pos + 3);

答案 2 :(得分:0)

使用explode()函数,您可以根据分隔符将字符串拆分为数组。然后我采取了数组的最后一个元素,在字符串前加上“Hello”,并使用implode将它重新组合在一起!

$tdr="<p>Previous reports stated that the Pokemon Alpha.</p><p>On the other hand, Pokemon Diamond and Pearl are reported .</p><p>On the other hand, Pokemon Diamond and Pearl are reported.</p>";
$ex = explode("<p>", $tdr);


$new = "Hello." . $ex[3];

$finished = implode("<p>", array($ex[1], $ex[2], $new));

var_dump($finished);