我想比较两个字符串并突出显示匹配连续4个或更多单词的单词。
当字符串中有双倍空格或换行时,字符串变亮了,我遇到了问题。
例如
假设string1是Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,
graphic or web designs.
String2是laying out print, graphic
预期输出:
Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in <span style="color:red">laying out print,
graphic</span> or web designs.
PHP代码:
<?php
$str1 ="Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,
graphic or web designs.";
$str2 = "/laying out print, graphic/iu";
echo preg_replace($str2, '<span style="color:red">$0</span>', $str1);
?>
注意:String1格式应相同。
以下是完整的代码:https://3v4l.org/3pBFR
在此示例中,应突出显示$answer
中的最后一段,但不突出显示。
答案 0 :(得分:2)
执行此操作的一种方法是将$str2
中的任何空白替换为\s+
,然后它将匹配$str
中的任何空白序列。然后可以在当前操作中将其用于preg_replace:
$str1 ="Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,
graphic or web designs.";
$str2 = "laying out
print, graphic";
$regex = preg_replace('/\s+/', '\s+', $str2);
echo preg_replace("/$regex/iu", '<span style="color:red">$0</span>', $str1);
输出:
Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in <span style="color:red">laying out print,
graphic</span> or web designs.