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

时间:2016-04-15 06:25:35

标签: php arrays regex preg-replace

我如何在<i></i>This is line one!的{​​{1}}下方This is line two! This is line three!标记$thisStr `<i>This is line one!</i>` `<i>This is line two!</i>` `<i>This is line three!</i>` 标记,结果如下:< / p>

::

我所做的只是在$thisStr = 'This is line one! :: This is line two! :: This is line three!';个部分放置标签。我不能让它继续前进并包装标签。

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

<button id="button1">Click to copy</button>

3 个答案:

答案 0 :(得分:3)

这很好用,但不是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!'
*/

答案 1 :(得分:1)

如果你真的真的需要使用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不需要额外的复杂性。

答案 2 :(得分:0)

试试这个:

$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);

希望这有帮助。