Regex find words not followed by a letter

I iterate over a text string (in php) to change specific keywords in a database in links. The problem is that the words in the database exist inside each other, for example:

development, developer, development ...

As a result, I:

"Random string with the word <a href="developer"><a href="develop">develop</a>er</a> in it"

I would only need to wrap the tag around the developer , and not develop inside it ...

Here is my current function:

function hyper($haystack){ 
    $query = "SELECT * FROM `hyperwords` ";  
    $query .= "WHERE `active` = '1' ";
    $query .= "ORDER BY LENGTH(hyperword) DESC ";  
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result)){
        $needle = $row['hyperword'];
        $link = $row['link'];
        $haystack = preg_replace("/($needle)/iu", "<a class='meta' href='$link'>$1</a>", $haystack);
    }
    return $haystack;
}

Thanks in advance!

+3
source share
1 answer
$altered = preg_replace("/\b($needle)\b/iu", "<a class='meta' href='$link'>$1</a>", $altered);

- This is what you need:)

The metacharacter \ b is an anchor, similar to the carriage and dollar signs. This corresponds to a position called word boundary. This match is zero length.

. :)

+1

Source: https://habr.com/ru/post/1794031/


All Articles