这很容易。
<?php
$string = "Hello! How <a href=\"#\">are</a> you?!";
$stringTwo = "Hello! how are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "<a href=\"" . $link . "\">" . $word . "</a>", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)/", $string);
}
echo turnTheWordIntoALink($string, 'are', 'http://google.com');
echo turnTheWordIntoALink($stringTwo, 'are', 'http://google.com');
输出:
第一函数输出:Hello! How <a href="#">are</a> you?!
第二函数输出:Hello! how <a href="http://google.com">are</a> you?!
备选:
如果你想不检测<a>
标签,其被关闭,您可以使用此替代代码:
$stringThree = "Hello! how <a href=\"#\">are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "<a href=\"" . $link . "\">" . $word . "</a>", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)+(.)+(<\/a>)/", $string);
}
echo turnTheWordIntoALink($stringThree, 'are', 'http://google.com') . "\n";
这使输出:Hello! how <a href="#"><a href="http://google.com">are</a> you?!
我看到一个错字。 '?!'标记未关闭。这是故意的吗? –
看到这个:http://matthewjamestaylor.com/blog/convert-special-characters-to-html-entities-between-code-tags –
谢谢,是正确的。 – shozdeh