Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing the last occurrence of a character in a string

Tags:

php

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?

like image 475
willdanceforfun Avatar asked Feb 28 '11 06:02

willdanceforfun


2 Answers

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));
like image 180
poundifdef Avatar answered Oct 13 '22 23:10

poundifdef


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 [^ ]).

like image 24
alex Avatar answered Oct 14 '22 00:10

alex