简体   繁体   中英

PHP preg_replace remove all dot character from between square brackets

How do I remove all . characters from between two square brackets in a string using preg_replace?

I'm trying to replace only between square brackets and not other dots in the string. This should have worked, but somehow just gives a blank string. How do I write the regex for this?

$str = '[city.name][city.state][city.mayor][city.mayor.name](city.name)';
$str = preg_replace('/\[.*?\]/','',$str);
echo $str;
// output
[cityname][citystate][citymayor][citymayorname](city.name)

You may use

'~(?:\G(?!^)|\[)[^][.]*\K\.~' # For [strings]
'~(?:\G(?!^)|<)[^<>.]*\K\.~'  # For <strings>

Or, to make sure there is a close ] there, add a (?=[^][]*]) lookahead:

'~(?:\G(?!^)|\[)[^][.]*\K\.(?=[^][]*])~' # For [strings]
'~(?:\G(?!^)|<)[^<>.]*\K\.(?=[^<>]*])~'  # For <strings>

See the regex demo and a regex demo with lookahead .

Details

  • (?:\\G(?!^)|\\[) - a [ or end of the previous successful match
  • [^][.]* - any 0+ chars other than [ , ] and .
  • \\K - match reset operator
  • \\. - a dot
  • (?=[^][]*]) - a positive lookahead that requires a ] after any 0+ chars other than ] and [ immediately to the right of the current location.

PHP demo :

$str = '[city.name][city.state][city.mayor][city.mayor.name](city.name)';
echo preg_replace('~(?:\G(?!^)|\[)[^][.]*\K\.~', '', $str);

You could use \\G as in

(?:\G(?!\A)|\[)
[^\].]*\K\.

See a demo on regex101.com (mind the verbose mode).


Broken down, this says:

 (?: \\G(?!\\A) # match after the previous match (not the start) | # or \\[ # [ ) [^\\].]* # neither dot nor ] \\K # make the engine forget what's been matched before \\. # match a dot 

Use callback

$str = preg_replace_callback('/\[[^]]*\]/', function($m){
    return str_replace(".", "", $m[0]);
}, $str);

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