start search at end, use commas

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
action_owl
Forum Newbie
Posts: 2
Joined: Thu Oct 22, 2009 11:38 am

start search at end, use commas

Post 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.";
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: start search at end, use commas

Post by pickle »

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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: start search at end, use commas

Post 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
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.
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: start search at end, use commas

Post 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);
Last edited by ridgerunner on Mon Nov 02, 2009 11:20 pm, edited 1 time in total.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: start search at end, use commas

Post by pickle »

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.
User avatar
jwzumwalt
Forum Newbie
Posts: 5
Joined: Mon Dec 08, 2008 8:50 pm

Re: start search at end, use commas

Post 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";}
Post Reply