Page 1 of 1
start search at end, use commas
Posted: Thu Oct 22, 2009 11:56 am
by action_owl
I have a string of varying lenghts, and I need to match the first occurence of a comma starting the search from the end of the string.
here is my failing code:
Code: Select all
$str = "this, that, the other.";
$str = preg_replace('/,/', ', and ', $str);
I'm trying to get:
"this, that,
and the other.";
Re: start search at end, use commas
Posted: Thu Oct 22, 2009 2:51 pm
by pickle
Regex is expensive & in this case, not necessary.
Look into
strrpos()
Re: start search at end, use commas
Posted: Thu Oct 22, 2009 3:03 pm
by AbraCadaver
action_owl wrote:I have a string of varying lenghts, and I need to match the first occurence of a comma starting the search from the end of the string.
here is my failing code:
Code: Select all
$str = "this, that, the other.";
$str = preg_replace('/,/', ', and ', $str);
I'm trying to get:
"this, that,
and the other.";
Lot's of ways to skin that cat:
Code: Select all
$str = "this, that, the other.";
$str = substr_replace($str, " and", strrpos($str, ",") + 1, 0);
-Shawn
Re: start search at end, use commas
Posted: Thu Oct 22, 2009 7:57 pm
by ridgerunner
By adding a lookahead assertion, you can match just the last comma like this...
Code: Select all
$str = preg_replace('/,(?=[^,\r\n]+$)/', ', and', $str);
Re: start search at end, use commas
Posted: Mon Oct 26, 2009 10:00 am
by pickle
regex is very expensive. Avoid it if at all possible.
Re: start search at end, use commas
Posted: Tue Nov 03, 2009 1:51 pm
by jwzumwalt
I had a simular problem and thought this may help...
This will strip off all characters after the last comma
Code: Select all
if ($line_in =~ m/(^.*\,)/) {print "$1\n";}