PHP replace words to links except images

后端 未结 3 1244
后悔当初
后悔当初 2021-01-25 23:48

My code is

$words = array();
$links = array();
$result = mysql_query(\"SELECT `keyword`, `link` FROM `articles` where `link`!=\'\".$act.\"\' \") 
or die(mysql_er         


        
3条回答
  •  失恋的感觉
    2021-01-26 00:46

    Edit: I updated the code to work better.

    I'm unsure exactly what the issue is but looking at your code I wouldn't be surprised that the negative look behind regex isn't matching multiple word strings where the "keyword" is not the first word after the src or alt. It might possible to beef up the regex, but IMHO a complicated regex might be a little too brittle for your html parsing needs. I'd recommend doing some basic html parsing yourself and doing a simple string replace in the right places.

    Here's some basic code. There is certainly a much better solution than this, but I'm not going to spend too much time on this. Probably, rather than inserting html in a text node, you should create a new html a element with the right attributes. Then you wouldn't have to decode it. But this would be my basic approach.

    $text = "Lorem ipsum \"dolor dolor sit amet";
    
    $result = array(
      array('keyword' => 'lorem', 'link' => 'http://www.google.com'),
      array('keyword' => 'ipsum', 'link' => 'http://www.bing.com'),
      array('keyword' => 'dolor sit', 'link' => 'http://www.yahoo.com'),
    );
    
    $doc = new DOMDocument();
    $doc->loadHTML($text);
    $xpath = new DOMXPath($doc);
    
    foreach($result as $row) {
      if (!empty($row['keyword'])) {
        $search = $row['keyword'];
        $replace = ''.$row['keyword'].'';
    
        $text_nodes = $xpath->evaluate('//text()');
        foreach($text_nodes as $text_node) {
          $text_node->nodeValue = str_ireplace($search, $replace, $text_node->nodeValue);
        }
      }
    }
    
    echo html_entity_decode($doc->saveHTML());
    

    The $result data structure is meant to be similar to result of your mysql_fetch_array(). I'm only getting the children of the root for the created html DOMDocument. If the $text is more complicated, it should be pretty easy to traverse more thoroughly through the document. I hope this helps you.

提交回复
热议问题