willdanceforfun willdanceforfun - 10 months ago 44
PHP Question

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 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

Doesn't look as good as

Hello I am
a string

How does one do such a thing?

Answer Source
echo preg_replace('/\s(\S*)$/', ' $1', 'Hello I am a string');


Hello I am a string


\s matches whitespace characters. To match a space explictly, put one in (and change \S to [^ ]).