php preg_replace regex replace string between two string

不打扰是莪最后的温柔 提交于 2019-11-30 09:47:26

问题


I have the following problem: I want to replace (in php) a special character, but only if it's between two other characters. It tried to find a solution with with preg_replace but it doesn't work.

I want to replace every ; with a : which is between the " The Examples:

$orig_string= 'asbas;"asd;";asd;asdadasd;"asd;adsas"'

result should be:

'asbas;"asd:";asd;asdadasd;"asd:adsas"'

I tried several regexes but without any succes...

Two examples i tried:

$result = preg_replace('(?<=\")(.*)(;)(.*)(?=\")',':', $str);

$result = preg_replace('.*\".*(;).*\"',':', $str);

Can anybody help me?

Thanks a lot

V


回答1:


You need not use look arounds here. It can be written as

("[^";]*);([^"]*")

replace with \1:\2

Regex Demo

Test

preg_replace ("/(\"[^\";]*);([^\"]*\")/m", "\\1:\\2", 'asbas;"asd;";asd;asdadasd;"asd;adsas"' );
=> asbas;"asd:";asd;asdadasd;"asd:adsas"

Update:

;(?!(?:"[^"]*"|[^"])*$)

Just replace the matched ; with :

DEMO




回答2:


A simple understandable solution could be the use of preg_replace_callback:

$str = preg_replace_callback('/"[^"]+"/',
       function ($m) { return str_replace(";", ":", $m[0]); },
       $str);

"[^"]+" captures the quoted stuff to $m[0] where ; is replaced by :

See test at eval.in (link will expire soon)




回答3:


;(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)

Try this.Replace by :.See demo.

https://www.regex101.com/r/bC8aZ4/16




回答4:


What about string replace?

str_ireplace(';";', ':";', $orig_string);

asbas;"asd:";asd;asdadasd;"asd;adsas"



来源:https://stackoverflow.com/questions/28169732/php-preg-replace-regex-replace-string-between-two-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!