开发者

Regex to find words that are not followed by letter

开发者 https://www.devze.com 2023-02-12 14:21 出处:网络
I am looping over a text string (in php) to change certain keywords in a database into links. The problem is when words in the database exist within each other such as:

I am looping over a text string (in php) to change certain keywords in a database into links. The problem is when words in the database exist within each other such as:

develop, developer, development...

I end up with:

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

I would need this to only wrap an a tag around developer and not the develop within it...

Here is my current 开发者_JS百科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!!!


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

is what you need :)

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

see here for more information :)

0

精彩评论

暂无评论...
验证码 换一张
取 消