简体   繁体   中英

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

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. 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 () (');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM