开发者

function to replace strings except images with alt need to be adjust

i have my own SEO function it used to replace a word in string to clickable link this is the function

function myseo($t){
    $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    $a = array('computer','films', 'playstation');
    $uu = count($a);
    $theseotext = $t;
    for ($i = 0; $i < $uu; $i++) {
        $theseotext = str_replace($a[$i], '<a href="'.$url.'" title="'.$a[$i].'">'.$a[$i].'</a>', $theseotext);
    }
    return $theseotext;
}

it's working great with strings but when there is an image inside the string and this image have ALT="" or somtime TITLE="" the code got error and the images not showing.

this image before do the seo function:

<img src="mypic.jpg" alt="this is my computer pic" title="this is my computer pic" />

the image after do the seo function

<img src="mypic.jpg" alt="this is my <a href="index.php" title="computer">computer</a> pic" title="this is my <a href="index.php" title="computer">computer</a>pic" />

is there any way to let the code do not repl开发者_如何学JAVAace the word if it inside the TITLE or the ALT.


You can't make the str_replace approach context-sensitive. Using a DOM parser is obviously overkill as usual. But the simple workaround would be to just filter text content between existing tags.

Meaning you need a wrapper call around your existing rewrite function. This might suffice:

$html = preg_replace_callback('/>[^<>]+</', 'myseo', $html);
// Will miss text nodes before the first, or after the last tag.

You would have to adapt your callback slightly:

function myseo($t) {
    $theseotext = $t[0];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜