如何用 <p> 标签包围字符串,而 <p> 标签中已经没有 - PHP?

How to surround string with <p> tag that are not in <p> tag already - PHP?

我有一个 $text 字符串:

$text = "<body>
forth<br />
lalallalal<br />
lalal<br />
lalal2<br />
the first line
</body>";

还有一个 $array_of_strings :

$array_of_strings =  [
"the first line",
"lalallalal",
"lalal2",
"lalal",
"forth"
];

我需要将 $array_of_strings 中的每个字符串包围到 <p> 标签中

foreach ($array_of_strings as $string) {
    $text = str_replace($string, "<p>{$string}</p>", $text);
}

输出为var_dump($text);:

string(139) "<body>
<p>forth</p><br />
<p><p>lalal</p><p>lalal</p></p><br />
<p>lalal</p><br />
<p><p>lalal</p>2</p><br />
<p>the first line</p>
</body>"

如您所见,<p> 标签中有一个 <p> 标签。我怎样才能逃脱它并得到这样的输出:

string(132) "<body><p>
forth</p><br /><p>
lalallalal</p><br /><p>
lalal</p><br /><p>
lalal2</p><br /><p>
the first line
</p></body>"

您的某些 $array_of_strings 是其他字符串的子字符串。您还需要查找换行符,以便只获取您要查找的整个字符串。此外,一旦整理好 <p></p>,您可能就不需要 <br /> 标签了。

尝试按如下方式更改您的 str_replace

foreach ($array_of_strings as $string) {
    $text = str_replace($string."<br />", "<p>{$string}</p>", $text);
}

或者如果您需要将那些 <br /> 标签保留在那里:

foreach ($array_of_strings as $string) {
    $text = str_replace($string."<br />", "<p>{$string}</p><br />", $text);
}

尝试将您的循环与一些正则表达式结合起来。您得到这种不希望的结果的原因很明显:lalallalal 恰好是 lalal 的 2 倍,所以您应该期望 <p>lalal</p><p>lalal</p>。合乎逻辑吧?无论如何,您可以通过使用 Word Boundaries 构建正则表达式来绕过所有这些 str_replace,如下所示:

<?php

$text = "<body>
            forth<br />
            lalallalal<br />
            lalal<br />
            lalal2<br />
            the first line
        </body>";

$array_of_strings =  array(
    "the first line",
    "lalallalal",
    "lalal2",
    "lalal",
    "forth"
);


// BUILD A REGEX ARRAY FROM THE $array_of_strings
$rxArray        = array();
foreach($array_of_strings as $string){
    $rxArray[]  = "#(\b" . preg_quote( trim($string) ) . "\b)#si";
}

$text  = preg_replace($rxArray, "<p></p>", $text);

var_dump($rxArray);
var_dump($text);

以下是上述 2 var_dump() 次调用的结果,顺序如下:

array (size=5)
      0 => string '#(\bthe first line\b)#si' (length=24)
      1 => string '#(\blalallalal\b)#si' (length=20)
      2 => string '#(\blalal2\b)#si' (length=16)
      3 => string '#(\blalal\b)#si' (length=15)
      4 => string '#(\bforth\b)#si' (length=15)

string '<body>
    <p>forth</p><br />
    <p>lalallalal</p><br />
    <p>lalal</p><br />
    <p>lalal2</p><br />
    <p>the first line</p>
    </body>' (length=141)

自己确认一下HERE

简单方法:

$replace = [];
foreach ($array_of_strings as $string) {
    $replace[$string] = "<p>$string</p>";
}

echo strtr($text, $replace);