Hello!Somebody can help me please how can i autolink any word i have in my webpage autolink in php ?
example array

$word_list = array  (

    'dogs' => 'http://dogs.com', 
    'dog' => 'http://dogs.com', 
    'cat' => 'http://cats.com', 
    'kitten' => 'http://cats.com',
    'horse' => 'http://horses.com'
    )

any text dogs in my website corispond to link <a href="http://dogs.com">dogs</a>

Thank you in advance.

Dani AI

Generated

Short answer: for plain text the preg_replace route that suggested will work, but when your articles contain HTML you should not run blind regex replacements on the whole HTML — that can break tags, attributes or existing links. Use a DOM-based approach that only edits text nodes and skips anchors/code/pre/script/style nodes. DOMDocument class. preg_replace notes.

A safe workflow (high level)

  • Build a keyword => url map and normalize keys for case-insensitive matching.
  • Escape each keyword when you build the regex (use preg_quote). preg_quote
  • Sort keywords by length (longer first) to avoid partial matches (so "dog" does not steal "dogs").
  • Parse the article HTML with DOMDocument and find text nodes with DOMXPath; skip nodes inside a, code, pre, script, style.
  • Use preg_replace_callback on each text node to turn matched words into <a> HTML, then import the generated fragment back into the DOM. preg_replace_callback

Example (DOM-based, avoids changing tags or attributes):

<?php
function autolink_html($html, array $map, $limit = -1) {
    if (empty($map)) return $html;
    // normalize and sort keys
    $lookup = [];
    foreach ($map as $k => $u) $lookup[mb_strtolower($k,'UTF-8')] = $u;
    uksort($lookup, function($a,$b){ return mb_strlen($b,'UTF-8') - mb_strlen($a,'UTF-8'); });
    $escaped = array_map(function($w){ return preg_quote($w,'/'); }, array_keys($lookup));
    $pattern = '/\b(' . implode('|',$escaped) . ')\b/ui';

    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML(mb_convert_encoding($html,'HTML-ENTITIES','UTF-8'));
    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query('//text()[normalize-space(.)!=""]');

    foreach ($nodes as $node) {
        $p = $node->parentNode;
        if ($p && in_array(strtolower($p->nodeName), ['a','script','style','code','pre'])) continue;
        $new = preg_replace_callback($pattern, function($m) use ($lookup) {
            $k = mb_strtolower($m[0],'UTF-8');
            $url = $lookup[$k];
            return '<a href="'.htmlspecialchars($url,ENT_QUOTES,'UTF-8').'" rel="nofollow">'.htmlspecialchars($m[0],ENT_QUOTES,'UTF-8').'</a>';
        }, $node->nodeValue, $limit);
        if ($new !== $node->nodeValue) {
            $tmp = new DOMDocument(); $tmp->loadHTML('<?xml encoding="utf-8"?><div>'.$new.'</div>');
            $div = $tmp->getElementsByTagName('div')->item(0);
            while ($div && $div->hasChildNodes()) {
                $import = $doc->importNode($div->firstChild, true);
                $p->insertBefore($import, $node);
            }
            $p->removeChild($node);
        }
    }
    $body = $doc->getElementsByTagName('body')->item(0);
    $out = ''; foreach ($body->childNodes as $c) $out .= $doc->saveHTML($c);
    return $out;
}
?>

Notes and cautions

  • Limit replacements per node/page to avoid over-linking and poor UX/SEO; choose rel="ugc" or rel="sponsored" instead of nofollow when appropriate per Google guidance. Qualify outbound links for SEO
  • Test on copies (check encoding and edge cases) and watch performance if your map contains many thousands of keys.
  • This ties back to the preg_replace ideas in the thread, but applies them safely to HTML (so gets links without breaking markup). For small plain-text snippets, simpler preg_replace calls still work; for full HTML articles prefer the DOM approach above.

Recommended Answers

All 8 Replies

preg_replace is a good option. Where does the text come from?

I need in all articles have words like in array replace with links,make that tag link

Member Avatar for Member #949455

I need in all articles have words like in array replace with links,make that tag link

I assume you got the code snippet from here:

Like what pritaeas mention used preg_replace function.

I copy and paste the code from the link so it would be easier to follow:

// list of keywords to auto-link 
// list plural forms first
$reserved_word_list = array (
    'dogs' => 'http://dogs.com', 
    'dog' => 'http://dogs.com', 
    'cat' => 'http://cats.com', 
    'kitten' => 'http://cats.com',
    'horse' => 'http://horses.com'
}

// search text string and auto-link the words
foreach($reserved_word_list as $word => $rep_string){

if(strpos($some_text, $word)){

// link the word
$some_text = preg_replace('/(\s+)('.preg_quote($word).')/i','$1<a href="'.$rep_string.'">$2</a>',$some_text);

}
}

As you can see it does have preg_replace() function.

You can pass arrays to preg_replace:

$some_text = preg_replace(array_keys($reserved_word_list), array_values($reserved_word_list), $some_text);

But then you need to use correct patterns in your array:

$reserved_word_list = array (
    '/\bdog(s)?\b/' => 'http://dogs.com', 
    '/\bcat|kitten\b/' => 'http://cats.com', 
    '/\bhorse\b/' => 'http://horses.com'
}

Thank you for your time ,but i see i am not explaing very well . i do an example for that

<?php 
    $reserved_word_list = array (
    '/\bdog(s)?\b/' => 'http://dogs.com',
    '/\bcat|kitten\b/' => 'http://cats.com',
    '/\bhorse\b/' => 'http://horses.com'
    );
    $some_text = preg_replace(array_keys($reserved_word_list), array_values($reserved_word_list), $some_text);
    if (isset($some_text)) {
?>

bcat bdog  bhorse cat horse dog
<?php } ?>

In this code i need linking auto my words --> bcat bdog bhorse cat horse dog

Thank you another time.

Member Avatar for Member #949455

Thank you for your time ,but i see i am not explaing very well . i do an example for that

I feel English might not be your first language.

pritaeas already mention that:

But then you need to use correct patterns in your array

Another words he did most of the work and you need to test it out and find the correct pattern.

If you still having problems figuring it out then I would suggested you should pay pritaeas at least 30 euros = 30€

He would gladly finish the code to suited your version.

If you want me to do it I would charge 40 dollars = $40

Try this:

<?php
$text = 'The quick brown fox jumps over the lazy white dog and the small blacks dogs.';

$replaceList = array (
    '/\b(dog|dogs)\b/' => '<a href="http://dog.com">$1</a>',
    '/\b(fox)\b/' => '<a href="http://fox.com">$1</a>'
);

$newText = preg_replace(array_keys($replaceList), array_values($replaceList), $text);
echo $newText;
?>

Thank you pritaeas very appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.