Replace whitespace but only between limits php

Viewed 75

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.

3 Answers

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

There's probably a slicker regex for only one preg_replace but you can match between delimiters , replace spaces, and then replace in the string:

$string = 'whatever text including some $text between delimiters$ and...';
preg_match('/\$[^$]+\$/', $string, $matches);

foreach($matches as $match) {
    $replace = preg_replace('/\s+/', ':', $match);
    $string_replaced = preg_replace(preg_quote("/$match/"), $replace, $string);
}

This also allows for more than one delimited string in the string.

Try this,

$string = 'whatever text including some $text between delimiters$ and...';
//get substring without space
$sub = str_replace(' ','',substr($string,strpos($string,'$'),-strpos(strrev($string),'$')));
//replace sub string with new one 
echo substr_replace($string,$sub,strpos($string,'$'),-strpos(strrev($string),'$'));
Related