我有一个小问题,我正在努力寻找解决方案.
基本上,假设你有以下字符串:
$string = 'Hello I am a string';
Run Code Online (Sandbox Code Playgroud)
并且你希望以下面的内容结束:
$string = 'Hello I am a string';
Run Code Online (Sandbox Code Playgroud)
简单地说,用一个不间断的空间替换最后一个空格.
我这样做是因为我不希望标题中的最后一个字是独立的.仅仅因为在标题方面:
Hello I am a
string
Run Code Online (Sandbox Code Playgroud)
看起来不那么好
Hello I am
a string
Run Code Online (Sandbox Code Playgroud)
一个人怎么做这样的事情?
pou*_*def 23
这个例子中的代码可以解决问题:
// $subject is the original string
// $search is the thing you want to replace
// $replace is what you want to replace it with
substr_replace($subject, $replace, strrpos($subject, $search), strlen($search));
Run Code Online (Sandbox Code Playgroud)
echo preg_replace('/\s(\S*)$/', ' $1', 'Hello I am a string');
Run Code Online (Sandbox Code Playgroud)
Hello I am a string
Run Code Online (Sandbox Code Playgroud)
\s匹配空白字符.要明确匹配空格,请将其中一个(并更改\S为[^ ]).