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
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');
Hello I am a string
CodePad.
\s
matches whitespace characters. To match a space explictly, put one in (and change \S
to [^ ]
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With