CodeWhisperer
CodeWhisperer

Reputation: 1195

Find matches by word and check if it's a link or not

I want to create a PHP array like below, which contains two values, one for the matching word and one to check if the match is a link or not.

Input

$string = "test <a href=\"test\" title=\"test\">test</a>"

What can I do here to find all matches of the word 'test' and check if the founded match is a link or not?

Output

Array
(
    [0] => 
           Array 
           (
               [0] test
               [1] false
           )
    [1] => 
           Array 
           (
               [0] test
               [1] true
           )
)

Upvotes: 1

Views: 66

Answers (2)

trincot
trincot

Reputation: 350270

You could use a regular expression for this:

$string = 'test <a href="http://test" title="mytitle">link text</a>';

if (preg_match("#^\s*(.*?)\s*<a\s.*?href\s*=\s*['\"](.*?)['\"].*?>(.*?)</a\s*>#si",
         $string, $match)) {
    $textBefore = $match[1]; // test
    $href       = $match[2]; // http://test     
    $anchorText = $match[3]; // link text
    // deal with these elements as you wish...
}

This solution is not case-sensitive, it will work with <A ...>...</A> just as well. If the href value is delimited with single quotes instead of double quotes, it will still work. Surrounding spaces of each value are ignored (trimmed).

Upvotes: 1

Amar Shukla
Amar Shukla

Reputation: 136

Try this code :

<?php

    $string ="test <a href=\"test\" title=\"test\">test</a>";
    $link ='';
    $word = '';
    $flag = true;
     for($i=0;$i<strlen($string);$i++){

       if($string[$i] == '<' && $string[$i+1] == 'a'){
         $flag=false;
         while($string[$i++] != '>')
         {

         }
         while($string[$i] != '<' && $string[$i+1] != '/' && $string[$i+2] != 'a' && $string[$i+3] != '>'){
             $link .= $string[$i++];
           }
       }
       else{
        if($flag)
          $word.=$string[$i];
       }
     }
    echo 'Link :'.$link . "<br/>";
    echo 'Word:'.$word;
    // You can now manipulate Link and word as you wish 

    ?>

Upvotes: 0

Related Questions