开发者

Add links to specific words within span tag in PHP

开发者 https://www.devze.com 2023-02-03 10:16 出处:网络
I have a list of words that I\'d like to add a link to, I can do this fairly easily using preg_match_all and preg_replace:

I have a list of words that I'd like to add a link to, I can do this fairly easily using preg_match_all and preg_replace:

$str = "<span class=\"cz\">Dám si j开发者_C百科edno pivo prosím.</span> = I'll have a beer please.";

preg_match_all('/[a-zťúůýžáčďéěíňóřš]+/i',$str,$matches);
$matches = array_unique($matches[0]);

foreach ($matches as $match) {
    if(!empty($words[$match])) {
        $str = preg_replace("/(^|[^\w]){1}(".preg_quote($match,"/").")($|[^\w]){1}/i", '\\1<a href="#">\\2</a>\\3', $str);
    }
}

echo $str;

What I'd like to do is restrict the linking to only within the span tag.

My brain is all regex-ed out, so any help would be appreciated! Thanks!

Darren.


preg_match_all('/[a-zťúůýžáčďéěíňóřš]+(?=\s*?</span>)/i',$str,$matches);


/( *<SPAN*>)([^<]*)(<\/SPAN>)/i

I think something like this should work, but will break if you have other tags inside your SPAN. I'd advise you to use the DOM functions instead.

0

精彩评论

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