Replacing the last occurrence of a character in a string
I have a little issue I'm trying to find a solution for.
Basically, imagine you have the following string:
$string = 'Hello I am a string';
And you'd like it to end with something like the folowing:
$string = 'Hello I am a&开发者_如何学JAVAnbsp;string';
Simply, replacing the last occurrence of a space, with a non-breaking space.
I'm doing this because I don't want the last word in a heading to be on its own. Simply because when it comes to headings:
Hello I am a
string
Doesn't look as good as
Hello I am
a string
How does one do such a thing?
Code from this example will do the trick:
// $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));
echo preg_replace('/\s(\S*)$/', ' $1', 'Hello I am a string');
Output
Hello I am a string
CodePad.
\s
matches whitespace characters. To match a space explictly, put one in (and change \S
to [^ ]
).
This would do the trick:
$string = preg_replace('/([\s\S]+)\s(\w)$/','$1 $2',$string);
as per pounndifdef's answer, however i needed to decode the
HTML entity like so:
substr_replace($subject, html_entity_decode($replace), strrpos($subject, $search), strlen($search));
also worked using alex's answer:
preg_replace('/\s(\S*)$/', html_entity_decode(' ').'$1', 'Hello I am a string');
Use str_replace()
like normal, but reverse the string first. Then, reverse it back.
精彩评论