且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动将单词转换为PHP中的链接

更新时间:2023-02-19 21:36:03

为更好地阐明问题,

我有一个带有一些标签的HTML代码.我想要其中的一些单词,转换为一些链接.但是,如果是另一个链接,则不会转换.请参阅以下高级示例,获取要链接到 google 的特殊单词you:

I have a HTML code that have some tags. I want some words in that, converted to some links. But if it is a another link does not convert. See below advanced example for special word you that we want linked to the google:

This <a href="#">is a sample</a> text. Hello?! How are you?! <a href="#1">Are you ready</a>?!

This <a href="#">is a sample</a> text. Hello?! How are you?! <a href="#1">Are you ready</a>?!

应转换为:

This <a href="#">is a sample</a> text. Hello?! How are <a href="http://www.google.com">you</a>?! <a href="#1">Are you ready</a> ?!

This <a href="#">is a sample</a> text. Hello?! How are <a href="http://www.google.com">you</a>?! <a href="#1">Are you ready</a> ?!

注意 ,第一个you已更改,但第二个you未被更改,因为它位于另一个<a>标记中.

Note that the first you changed, but that second you was not changed, because it's in the another <a> tag.

答案:

由于这项工作存在正则表达式问题,因此无需正则表达式就可以解决此问题.这里给出一个简单的解决方案:

Because of this work has issue with regular expression, this problem can solve without regular expression. Here a simple solution is given:

    $data = 'Hello! This is a sample text.          <br/>'.
    'Hello! This <a href="#1">is</a> a sample text.   <br/>'.
    'Hello! This <a href="#2">is a sample text.</a>   <br/>'.
    'Hello! <a href="#3">This is a sample</a> text.   <br/>'.
    '<a href="#4">Hello! This</a> is a sample text.';

    $from = " is ";
    $to   = '<a href="http://www.google.com" > '.$from.' </a>';

    echo $data;
    $data =  explode($from, $data);
    echo "<br><br>";

    echo $data[0];
    $diff = 0;
    for($i=1; $i<count($data); $i++){
        $n = substr_count($data[$i-1], '<a ') + substr_count($data[$i-1], '<A ');
        $m = substr_count($data[$i-1], '</a>') + substr_count($data[$i-1], '</A>'); 

        $diff += $n-$m;
        if($diff==0)
            echo $to.$data[$i];
        else
            echo $from.$data[$i];
    }