Norman
Norman

Reputation: 6365

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)

Upvotes: 2

Views: 2277

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

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);

Upvotes: 2

schorsch
schorsch

Reputation: 11

Use callback

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

Upvotes: 1

Jan
Jan

Reputation: 43169

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

Upvotes: 1

Related Questions