Search code examples
phppreg-replacehref

automatic convert word to link in PHP


I want write a simple code that convert special words to special link (for wiki plugin), if it's not a link!

For example suppose we have a text "Hello! How are you?!" and
we want convert are to <a href="url">are</a>, but if we have <a href="#"> Hello! How are you</a>?! or Hello! <a href="url">How are you?!</a> does not change. Because it's a link.

How can I do it in PHP?! With preg_replace?! How to?

Thanks.


Solution

  • To better clarify the issue:

    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>?!

    should be convert to:

    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> ?!

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


    Answer:

    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];
        }