Okan Kocyigit
Okan Kocyigit

Reputation: 13441

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: <a 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.

Upvotes: 0

Views: 787

Answers (3)

ridgerunner
ridgerunner

Reputation: 34435

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'

Upvotes: 2

mario
mario

Reputation: 145512

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.

Upvotes: 3

hsz
hsz

Reputation: 152294

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.

Upvotes: 1

Related Questions