我想替换帖子内容中的几个字。例如
原件:
Here is my test string.
Which Need to Replace First Test word in the string.
例外字符串:
Here is my <a href="link"> test </a> string.
Which Need to Replace First Test word in the string.
我已经试过了,但我很少遇到问题。
当该单词与单词一起具有预定义链接时。喜欢
Here is my <a href="test case link"> test Case </a> string.
Which Need to Replace First Test word in the string.
所以我的函数把它分解成两个词
Here is my <a href="link"> test </a> <a href="test case link"> Case </a> string.
Which Need to Replace First Test word in the string.
==我的解决方案====
add_filter(\'the_content\' , \'update_content\');
function update_content($content){
if((is_singular()){
$termsList = array(
\'test\' => \'<a href="test">test</a>\'
);
foreach($termsList as $word => $term_link){
//$content = str_replace($word , $replacement , $content , $count);
//Convert into Smaller Case
$str_content = strtolower($content);
$str_word = strtolower($word);
//Get the position of the word
$position = strpos($str_content, $str_word , 0);
//Get the Exact word with case sensitive
$match_string = substr ($content , $position , strlen($word) );
//Prepare Replacement
$replacement = \'<a href="\'.$term_link.\'">\'.$match_string.\'</a>\';
if(!empty($position)){
//Replace The word
$content = substr_replace($content, $replacement, $position, strlen($word));
}
}
}
return $content;
}
SO网友:cjbj
如果您想考虑所有可能性,这是一个相当复杂的PHP(而不是WP)问题。
如果更换test
具有<a href="#">test</a>
如果内容已经<a href="?">test</a>
, 因为结果是<a href="?"><a href="#">test</a></a>
因此,在更换之前,您需要查看test
已是链接。这并不是那么简单,因为您不能简单地扫描<a href="...">test</a>
. 毕竟,你可能有<a href="...">this is my test, yeah!
. 或test
可能是另一个单词的子字符串,如protesting
. 为了防止后者成为目标,您可以检查test
, 但你可能会错过test,
.
另一件需要考虑的事情是:如果已经有链接test
, 你想保留还是替换它?
因此,根据您的需要,您必须构建regular expression 这会对您的内容进行复杂的模式识别,以确保它完全符合您的需要。有关正则表达式的帮助,try Stack Overflow.