It's easy.
<?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');
Output:
First function output: Hello! How <a href="#">are</a> you?!
Second function output: Hello! how <a href="http://google.com">are</a> you?!
Alternative:
If you want to not detect <a>
tags which were closed, you can use this alternative code:
$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') . "
";
This gives the output: Hello! how <a href="#"><a href="http://google.com">are</a> you?!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…