按单词查找匹配项并检查它是否是链接


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

我想创建一个如下所示的PHP数组,其中包含两个值,一个用于匹配单词,另一个用于检查匹配是否是链接。

输入

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

我能在这里做什么来找到单词"test"的所有匹配项并检查建立的匹配项是否是链接?

输出

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

你可以为此使用正则表达式:

$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...
}

此解决方案不区分大小写,它也适用于<A ...>...</A>。如果 href 值用单引号而不是双引号分隔,它仍然有效。每个值的周围空间将被忽略(修剪)。

试试这段代码:

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