Replace whitespace but only between limits php

Alvaro Franz :

I want to replace whitespaces with another string using PHP.

I do it as follows:

$string = 'whatever text including some $text between delimiters$ and...';
$string_replaced = preg_replace('/\s\s+/', '\:', $string);

But it replaces all the spaces in the string, which is very logic.

I only want the regex to apply between the $ delimiters.

In the official preg_replace() docs, I do not find anything that might help.

So I guess I am missing some PHP feature that will allow this.

Wiktor Stribiżew :

You may use preg_replace_callback to match all texts between $ symbols with '/\$[^$]*\$/' and then replace 1+ whitespaces only inside these matched texts:

$string = 'whatever text including some $text between delimiters$ and...';
$string_replaced = preg_replace_callback('~\$[^$]*\$~', function($m) {
   return preg_replace('~\s+~u', ':', $m[0]);
}, $string);

See the PHP demo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=301542&siteId=1