开发者

Using preg_replace(), how to only replace matched text if it is shorter than 10 characters?

$str = "(search: kewyord)";
$str = preg_replace("'\(search: (.*)\)'Ui","(search: <开发者_如何学Ca href=\"search.php?q=\\1\"><b>\\1</b></a>)",$str);
//result->>
$str =  (search: <a href=\"search.php?q=keyword\">kewyord</a>)

I wanna change as

if keyword is more than 10 characters, don't replace it.

how can I do that? Thanks.


To make it match a minimum length you can replace the * with a numeric quantifier {10,}. But you wanted to opposite, so this would do:

 preg_replace("'\(search: (.{1,9})\)'Ui",

See http://www.regular-expressions.info/repeat.html under Limiting Repetition.


Please don't use the 'U' modifier! (it is bad style, never necessary and serves only to confuse). Instead, apply the universal ? lazy modifier to any quantifiers you wish to be lazy. The dot is also rarely needed. This is probably what you're after:

'/\(search:\s+([^)\s]{1,9})\)/i'


You can use preg_match with your regex, then use strlen() function on matched string.

If matched string's length > 10 then use str_replace with matched string as a first param.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜