這很容易。
<?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