Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.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将字符串中的关键字替换为href链接_Php_Preg Match_Str Replace - Fatal编程技术网

PHP将字符串中的关键字替换为href链接

PHP将字符串中的关键字替换为href链接,php,preg-match,str-replace,Php,Preg Match,Str Replace,我“今天早上很胖”,所以请原谅这个简单的问题-我有一个关键字数组,例如array('keyword1','keyword2'…),我有一个文本字符串-(长度有点像博客内容,即不只是几个字,可能是200-800字)在字符串中搜索关键字并将其替换为href链接的最佳方法是什么。因此,在文本中,“关键字1”(作为纯文本)将变成,依此类推 看,赛义德今天早上很胖 非常感谢。典型案例: $text=“有一些文本关键字1和lorem ipsum关键字2。”; $keywords=array('keyword

我“今天早上很胖”,所以请原谅这个简单的问题-我有一个关键字数组,例如
array('keyword1','keyword2'…)
,我有一个文本字符串-(长度有点像博客内容,即不只是几个字,可能是200-800字)在字符串中搜索关键字并将其替换为href链接的最佳方法是什么。因此,在文本中,“关键字1”(作为纯文本)将变成
,依此类推

看,赛义德今天早上很胖

非常感谢。

典型案例:

$text=“有一些文本关键字1和lorem ipsum关键字2。”;
$keywords=array('keyword1','keyword2');
$regex='/('.introde('|',$keywords)。')/i';
//您可能希望使替换字符串更依赖于
//关键词匹配,但你必须告诉我们更多
$output=preg_replace($regex,,$text);
打印(输出);


现在,从
href
不是匹配关键字的函数的意义上讲,上述内容并不是一个非常“智能”的替换,而实际上,您可能希望这样做。在此处查看更多灵活性,或者编辑问题并提供有关您目标的更多信息。

为什么要使用正则表达式而不是str_replace()!?Regex是有效的,但它使如此简单的问题变得过于复杂。

Perfect Thank正是我想要的,只是出于兴趣,有没有办法在第一次出现关键字时只“匹配”一个关键字?@RussellParrott:只匹配任何一个关键字的第一个实例是非常重要的。匹配每个关键字的第一个实例并不是那么简单;您可能需要对每个循环中限制为1的关键字执行
preg\u replace
,或者(最好)使用
preg\u replace\u回调
,“记住”哪些关键字已经匹配至少一次,并将关键字本身作为已经看到的关键字的替换返回。
$text = "There is some text keyword1 and lorem ipsum keyword2.";
$keywords = array('keyword1', 'keyword2');

$regex = '/('.implode('|', $keywords).')/i';

// You might want to make the replacement string more dependent on the
// keyword matched, but you 'll have to tell us more about it
$output = preg_replace($regex, '<a href="apage">\\1</a>', $text);

print_r($output);