开发者

preg_replace only replaces first occurrence then skips to next line [duplicate]

This question already has answers here: My regex is matching too much. How do I make it stop? [duplicate] (5 answers) 开发者_StackOverflow社区 Closed 4 years ago.

Got a problem where preg_replace only replaces the first match it finds then jumps to the next line and skips the remaining parts on the same line that I also want to be replaced.

What I do is that I read a CSS file that sometimes have multiple "url(media/pic.gif)" on a row and replace "media/pic.gif" (the file is then saved as a copy with the replaced parts). The content of the CSS file is put into the variable $resource_content:

$resource_content = preg_replace('#(url\((\'|")?)(.*)((\'|")?\))#i', '${1}'.url::base(FALSE).'${3}'.'${4}', $resource_content);

Does anyone know a solution for why it only replaces the first match per line?


Try:

$resource_content = preg_replace('#(url\((\'|")?)(.*?)((\'|")?\))#i', '${1}'.url::base(FALSE).'${3}'.'${4}', $resource_content);

That will keep the (.*) term from matching "too much" content.


make an example - If your $variable is:

STARTING 
FIRSTT AAA 
SECONDD AAA

1) if you implement this function:

$variable = preg_replace('/STARTING(.*)AAA/', 'REPLACING_STRING', $variable);

it changes everything (from the STARTING to the latest AAA) and the result is:

REPLACING_STRING

2) if you use:

$variable = preg_replace('/STARTING(.*?)AAA/', 'REPLACED_STRING', $variable);

The Result is:

REPLACING_STRING 
SECOND AAA
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜