如何用<p>标签包围不在</p> <p>标签中的字符串 - PHP?

时间:2016-06-27 10:27:23

标签: php preg-replace str-replace

我有一个$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>"

3 个答案:

答案 0 :(得分:2)

简单方法:

$welcome = 'Welcome to the %s!';
$cms = 'CrappyCMS';
echo sprintf($welcome, $cms);
// echoes: Welcome to the CrappyCMS!

答案 1 :(得分:1)

你的一些$ array_of_strings是其他的子串。您还需要查找换行符,以便只获取您要查找的整个字符串。此外,一旦您排除了<br />,您可能不需要<p></p>代码。

尝试更改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);
}

答案 2 :(得分:1)

尝试将Loop与某些正则表达式结合使用。您获得如此不良后果的原因显而易见:lalallalal正好是lalal的2倍,因此您应该期待<p>lalal</p><p>lalal</p>。逻辑吧?无论如何,您可以通过使用str_replace构建正则表达式来绕过所有Word Boundaries

<?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>$1</p>", $text);

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

以下是各自订单中上述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