Any questions involving matching text strings to patterns - the pattern is called a "regular expression."
Moderator: General Moderators
action_owl
Forum Newbie
Posts: 2 Joined: Thu Oct 22, 2009 11:38 am
Post
by action_owl » Thu Oct 22, 2009 11:56 am
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.";
pickle
Briney Mod
Posts: 6445 Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:
Post
by pickle » Thu Oct 22, 2009 2:51 pm
Regex is expensive & in this case, not necessary.
Look into
strrpos()
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
AbraCadaver
DevNet Master
Posts: 2572 Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:
Post
by AbraCadaver » Thu Oct 22, 2009 3:03 pm
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
mysql_function(): WARNING : This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
ridgerunner
Forum Contributor
Posts: 214 Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT
Post
by ridgerunner » Thu Oct 22, 2009 7:57 pm
By adding a lookahead assertion, you can match just the last comma like this...
Code: Select all
$str = preg_replace('/,(?=[^,\r\n]+$)/', ', and', $str);
Last edited by
ridgerunner on Mon Nov 02, 2009 11:20 pm, edited 1 time in total.
pickle
Briney Mod
Posts: 6445 Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:
Post
by pickle » Mon Oct 26, 2009 10:00 am
regex is very expensive. Avoid it if at all possible.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
jwzumwalt
Forum Newbie
Posts: 5 Joined: Mon Dec 08, 2008 8:50 pm
Post
by jwzumwalt » Tue Nov 03, 2009 1:51 pm
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";}