Replace whitespace but only between limits php

无人久伴 提交于 2021-02-16 14:37:28

问题


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.


回答1:


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




回答2:


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.




回答3:


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),'$'));


来源:https://stackoverflow.com/questions/60706365/replace-whitespace-but-only-between-limits-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!