仅匹配正则表达式保留大小写的一部分

Lets say I want to replace a word saved in a string. I want to replace that word with the same word, that I have stored with the first letter as lower-case in a variable, adding html tags in the expression. I do care the case sensitivity in all letters but first.

So far: no problem.

But when I replace the expression, it always returns me the first letter with lower-case. And I wanted to replace all of them with their case. Example:

Subject: "<p>Lucky said that lucky is an unlucky word.</p>"

Word stored and searched: "lucky"

What I'd love to have: "<p><b>Lucky</b> said that <b>lucky</b> is an unlucky word.</p>"

That's what I've tried:

$word="lucky";
$result=preg_replace("/\b(?i)".substr($word,0,1)."(?-i)".substr($word,1)."\b/","<b>".$word."</b>","<p>Lucky said that lucky is an unlucky word.</p>");

It returns:

<p><b>lucky</b> said that <b>lucky</b> is an unlucky word.</p>

First lucky does not keep the "L".

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐