PHP的preg_replace正则表达式替换两个字符串之间的字符串 [英] php preg_replace regex replace string between two string

查看:111
本文介绍了PHP的preg_replace正则表达式替换两个字符串之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:我想替换(在php中)一个特殊字符,但前提是它位于其他两个字符之间.它试图用preg_replace找到一个解决方案,但是不起作用.

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"'

结果应为:

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

我尝试了多个正则表达式,但没有成功...

I tried several regexes but without any succes...

我尝试过两个示例:

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

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

有人可以帮助我吗?

非常感谢

V

推荐答案

您无需在此处使用环顾四周.可以写成

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

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

替换为\1:\2

正则表达式演示

测试

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

更新:

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

只需将匹配的;替换为:

演示

这篇关于PHP的preg_replace正则表达式替换两个字符串之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆