PHP REGEX用<p> -Tags中的URLS替换字符串

Heyho,

I want to replace some words with links, but only within the first 3 p-tags ($limit_p = 3) and only the first occurence in the p-tags together. The wordlist and linklist are in different arrays. I have a preg_replace_callback-function to replace it. It works fine, but has some issues if a word is part of another word and it replaces it each time:

$text = "<p>Lorem ipsum Hello World lorem ipsum.</p><p>Hello you</p>";
$arr1 = array('/ Hello World '/,'/ Hello /');
$arr2 = array(' <a href="link2">Hello World"</a> ',' <a href="link1">Hello</a> ');
$limit_p = 3;
$limit_tag = 1;
$res = preg_replace_callback(
    '/(<p[^>]*>)(.+?)(<\/p>)/Ui', 
      function ($m) use (&$arr1, &$arr2, &$limit_tag) {
        list (, $s, $t, $e) = $m;
        $t = preg_replace($arr1, $arr2, $t, $limit_tag);
        //$t = str_replace($find, $repl, $t);
        return "$s$t$e";
      },
      $text, $limit_p
    );

What I get is:

<p>Lorem ipsum <a href="link2"><a href="link1">Hello</a> World</a> lorem ipsum.</p><p><a href="link1">Hello</a> you</p>

What I want is:

<p>Lorem ipsum <a href="link2">Hello World</a> lorem ipsum.</p><p><a href="link1">Hello</a> you</p>

So I want to replace it only, if it is not within an a-tag. If the same word is in 2 p-tags it is replaced both times, which I dont want. Only the first occurence should be replaced.

Can you help me, please?

Thanks so much!

I have this solution now with the help from Niet:

$dom = new DOMDocument();
    // loadXml needs properly formatted documents, so it's better to use loadHtml, but it needs a hack to properly handle UTF-8 encoding
    $previous_value = libxml_use_internal_errors(TRUE);
    $dom->loadHtml(mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8"));
    libxml_clear_errors();
    libxml_use_internal_errors($previous_value);
    $xpath = new DOMXPath($dom);
    foreach($xpath->query('//text()[not(ancestor::a) and (ancestor::p) and not(ancestor::strong)]') as $node)
    {
            $replaced = preg_replace_callback(
                '/\b(?:('.implode(')|(',$arr1).'))\b/',
                function($m) use (&$arr1,&$arr2) {
                    // find which pattern matched
                    array_shift($m);
                    $result = array_filter($m);
                    $keys = array_keys($result);
                    $matched = $keys[0];
                    // apply match and remove from search list
                    $result = @$arr2[$matched];
                    unset($arr1[$matched], $arr2[$matched]);
                    return $result;
                },
                $node->wholeText, -1
            );
        //$replaced = str_ireplace('match this text', 'MATCH', $node->wholeText);
        $newNode  = $dom->createDocumentFragment();
        if($replaced && $replaced != "")
            $newNode->appendXML($replaced);
        $node->parentNode->replaceChild($newNode, $node);
    }
    // get only the body tag with its contents, then trim the body tag itself to get only the original content
    return mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");

Its working fine, but the html-code must be valid and crashes sometimes (I'm pretty sure mine is valid), but I get this error: Warning: DOMDocumentFragment::appendXML(): Entity: line 1: parser error : xmlParseEntityRef: no name in [...] on line

The problem is that you are performing the replacements in order.

Instead, try applying them all at once:

Have $arr1 like so:

$arr1 = array("Hello World","Hello");

And in your deepest code:

$t = preg_replace_callback(
    '/\b(?:('.implode(')|(',$arr1).'))\b/',
    function($m) use (&$arr1,&$arr2) {
        // find which pattern matched
        array_shift($m);
        $result = array_filter($m);
        $keys = array_keys($result);
        $matched = $keys[0];

        // apply match and remove from search list
        $result = $arr2[$matched];
        unset($arr1[$matched], $arr2[$matched]);
        return $result;
    },
    $t
);

Assuming I haven't messed it up, this should work quite well.

How about

$text = "<p>Lorem ipsum Hello World lorem ipsum.</p><p>Hello you</p>";
$arr1 = array('Hello World','Hello');
$arr2 = array('<a href="link2">Hello World</a>','<a href="link1">Hello</a>');

print strtr($text, array_combine($arr1, $arr2));

// <p>Lorem ipsum <a href="link2">Hello World</a> lorem ipsum.</p><p><a href="link1">Hello</a> you</p>