php preg_replace regex 替换两个字符串之间的字符串 [英] php preg_replace regex replace string between two string

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

问题描述

我有以下问题:我想替换(在 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"

更新:

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

只需将匹配的 ; 替换为 :

Just replace the matched ; with :

演示

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

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