[英]How to replace specific character such as bracket in php
I have been trying for the past three days to replace a bracket within my own delimiter. 在过去的三天里,我一直在尝试在自己的定界符中替换括号。 Something like
就像是
( ( [take] function ( [/take] (
To look like 看起来像
[take] function [ [/take]
Without affecting brackets outside of the [take][/take]
delimiters 不影响
[take][/take]
分隔符之外的方括号
I have tried 我努力了
preg_replace('/[^\[take\]]([)[^\[\take\]]/', '[', $string);
You'll need to use a regular expression: 您需要使用正则表达式:
$string = "( ( [take] function( [/take] (";
$result = preg_replace_callback(
"/(\[take\])(.*?)(\[\/take\])/",
function($m) {return $m[1] . str_replace("(", "[", $m[2]) . $m[3];},
$string
);
echo $result;
preg_replace_callback()
allows you to execute a callback function on the match. preg_replace_callback()
允许您在比赛中执行回调函数。 In this case we use matching groups (within parentheses) to isolate the text between the tags, and then in the callback replace the parenthesis with a bracket. 在这种情况下,我们使用匹配组(在括号内)来隔离标签之间的文本,然后在回调中用括号将括号替换。
如果间距一致,则:
$result = str_replace('function ()', 'function []', '( ( function () (');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.