php替换大括号内的文字

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php替换大括号内的文字相关的知识,希望对你有一定的参考价值。

字符串 $data['orderno']="fewewfewfewfwefewfwefef[dewfew]dweqfewfewfewfewf[3432534]";
$reg = '/\[(\w+)\]/';
$data['orderno'] = preg_replace($reg,'[1111111]',$data['orderno']);
输出:$data['orderno']="fewewfewfewfwefewfwefef[1111111]dweqfewfewfewfewf[1111111]";

我怎么没法替换数组里头的值呢?就是把dewfew 改成1111111。
不好意思,要替换的内容还有文字的情况。
$data['orderno']="fewewfewfewfwefewfwefef[啊啊啊啊]dweqfewfewfewfewf[哇哇哇哇]";
请问这个时候怎么替换呢?
$data['orderno']="fewewfewfewfwefewfwefef[你好]dweqfewfewfewfewf[你好]";

$data['orderno']="fewewfewfewfwefewfwefef[dewfew]dweqfewfewfewfewf[3432534]";
echo '原始字串:'.$data['orderno'].'<br>';
$reg = '/\[[\w]+]/';
$data['orderno'] = preg_replace($reg,'[1111111]',$data['orderno']);
echo '替换后:'.$data['orderno'];追问

不好意思,要替换的内容还有文字的情况。
$data['orderno']="fewewfewfewfwefewfwefef[啊啊啊啊]dweqfewfewfewfewf[哇哇哇哇]";
请问这个时候怎么替换呢?
$data['orderno']="fewewfewfewfwefewfwefef[你好]dweqfewfewfewfewf[你好]";

追答

$data['orderno']="fewewfewfewfwefewfwefef[啊啊啊啊]dweqfewfewfewfewf[哇哇哇哇]";
echo '原始字串:'.$data['orderno'].'';
$reg = '/\[[^x00-xff\w]+]/';
$data['orderno'] = preg_replace($reg,'[你好]',$data['orderno']);
echo '替换后:'.$data['orderno'];

追问

好像不行吧。
$str = $data['orderno'];
$reg = '/\[[^x00-xff\w]+]/';
$str = preg_replace($reg,'[NG工程状况]',$str);

追答

我不知道你是怎么说不行的,我这边是可以的,输出如下:
原始字串:fewewfewfewfwefewfwefef[啊啊啊啊]dweqfewfewfewfewf[哇哇哇哇]
替换后:fewewfewfewfwefewfwefef[NG工程状况]dweqfewfewfewfewf[NG工程状况]

代码:
$data['orderno']="fewewfewfewfwefewfwefef[啊啊啊啊]dweqfewfewfewfewf[哇哇哇哇]";
echo '原始字串:'.$data['orderno'].'';
$reg = '/\[[^x00-xff\w]+]/';
$data['orderno'] = preg_replace($reg,'[NG工程状况]',$data['orderno']);
echo '替换后:'.$data['orderno'];

追问

难道我是日文的windows系统吗

参考技术A echo preg_replace('|\[([a-z]+)\]|isU','11111111',$str);

以上是关于php替换大括号内的文字的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 .format() 打印字符串,并在替换的字符串周围打印文字大括号 [重复]

如何替换Notepad ++中两个括号内的字符?

替换括号内的逗号

用于匹配大括号中的每一行的正则表达式

捕获大括号内的内容

使用RegEx通过转义获取用大括号括起来的字符串