Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在某些单词周围加上标签_Php_Regex_Tags - Fatal编程技术网

Php 在某些单词周围加上标签

Php 在某些单词周围加上标签,php,regex,tags,Php,Regex,Tags,我有一系列的词,比如: array("the", "over", "hen"); "The quick brown fox jumps over the lazy hen" <strong>Hen</strong> #2 and <strong>ThE</strong> <strong>oveR</strong> reactive cow 我还有这样一个字符串: array("the", "over", "hen");

我有一系列的词,比如:

array("the", "over", "hen");
"The quick brown fox jumps over the lazy hen"
<strong>Hen</strong> #2 and <strong>ThE</strong> <strong>oveR</strong> reactive cow
我还有这样一个字符串:

array("the", "over", "hen");
"The quick brown fox jumps over the lazy hen"
<strong>Hen</strong> #2 and <strong>ThE</strong> <strong>oveR</strong> reactive cow
我想在数组中出现的所有单词周围加上一个标记(
strong
),但保持大小写正确

例如,使用前一个字符串,它将以

<strong>The</strong> quick brown fox jumps <strong>over</strong the lazy <strong>hen</strong>
看起来是这样的:

array("the", "over", "hen");
"The quick brown fox jumps over the lazy hen"
<strong>Hen</strong> #2 and <strong>ThE</strong> <strong>oveR</strong> reactive cow
母鸡#2和母牛过度反应

我猜答案会使用正则表达式,但我不太擅长…

我认为这应该行得通,试试看:)

$replaceWords=数组(“the”、“over”、“hen”);
$string=“敏捷的棕色狐狸跳过懒惰的母鸡”;
$string_words=explode(“,$string);
foreach$string_单词为$i=>$word{
if(FALSE==数组搜索(strtolower($word),$replaceWords))
继续;
$string_words[i]=“”$strin_words[i]。“”;
}
$new\u string=内爆(“,$string\u单词);
echo$new_字符串;
尝试以下操作:

$string = 'Then quick brown fox jumps over the lazy hen';
$keys = array('the', 'over', 'hen');

$patterns = array();
foreach($keys as $key)
    $patterns[] = '/\b('.$key.')\b/i';

echo preg_replace($patterns, '<strong>$0</strong>', $string);
$string='然后快速的棕色狐狸跳过懒惰的母鸡';
$keys=数组('the','over','hen');
$patterns=array();
foreach($key作为$key)
$patterns[]='/\b('.$key.')\b/i';
echo preg_replace($patterns,$0,$string);

您是否仅在比较过程中尝试转换为小写,然后使用原始标记替换/环绕您的标记?@Fluffeh您的意思是什么?你能举个例子说明我是如何做到的吗?不,所有被替换的单词都是小写的嗯,好吧,现在我得到你想要的了!否-不将第一个“the”改为粗体,即任何首字母大写且出现在字符串开头或句子后面的单词。不过我想我可能误解了你的问题。如果我遗漏了什么,请告诉我。