PHP在数组元素之前和之后添加文本


PHP add text before and after an arrays elements

如何在下面的$thisStr中将<i> </i>标签包裹在This is line one!This is line two!This is line three!周围,因此结果为:

`<i>This is line one!</i>`
`<i>This is line two!</i>`
`<i>This is line three!</i>`

我所做的只是在::部分添加标签。我无法让它来回移动并包装标签。

$thisStr = 'This is line one! :: This is line two! :: This is line three!';

echo preg_replace("/(::)/i", "<i>$1</i>", $thisStr);

这很好用,但不是preg_replace:

$thisStr = 'This is line one! :: This is line two! :: This is line three!';
$result= "<i>".str_replace("::","</i><i>",$thisStr)."</i>";
echo $result;

或者,为了匹配您的确切示例:

$thisStr = 'This is line one! :: This is line two! :: This is line three!';
$result= "'<i>".str_replace(" :: ","</i>'<br/>'<i>",$thisStr)."</i>'";
echo $result;
/*
'This is line one!'
'This is line two!'
'This is line three!'
*/

如果你真的真的需要使用preg_replace,这将适用于

$input_lines = "This is line one!
This is line two!
This is line three!";
$New_string = preg_replace("/This is line .*/", "<i>$0</i>", $input_lines);

该模式查找字符串"this is line",而.*表示任何长度的任何内容
那么替换模式就很容易理解了。

但我推荐Verjas写的答案
不需要preg_replace添加额外的复杂性。

试试这个:

$thisStr = 'This is line one! :: This is line two! :: This is line three!';
$lines = explode('::', $thisStr);
$result = '';
foreach($lines as $line) {
  $result .= '<i>' . $line .'</i>';
}
echo htmlentities($result);

希望这能有所帮助。