Jump to content

Reg ex Problem - Extract the string inside


supernoobie

Recommended Posts

:(

 

I need help if Reg ex is able to extract the string,

 

Here's my problem.

 

I want to extract the string inside the word "View" and ends in "return".

Sample:

  string = "View John Doe return"

 

I want to get the result "John Doe"

 

Is this possible in Regex?

 

Thanks In advance!  ;)

 

 

 

 

That's a bit complicated. If I understand correctly, all he needs is

 

preg_match_all('~^View (.*+) return$~', $string, $Matches);

 

(.*+) should be: (.*?) or (.+?), depending on whether it must match '0 or more' characters or '1 or more', respectively.

 

Edit: Also I can't see any real real point in using preg_match_all() with the start and end of string anchors.

Try this:

 

$str = 'View John,Doe ;return';

if (preg_match('/View(.*?);return/i', $str, $matches))
{
    print_r($matches);
}

 

You'll need to trim each match to remove any white space issues, but if this is user entered data you'd probably be better off trimming the data anyway; in-case they entered multiple spaces by accident. If this isn't user entered data you may wish to add the spaces back in like on the other examples.

 

I've also added the 'i' modifier to make the expression case-insensitive - again if it's user entered data it's probably a good idea.

supernoobie.. I'm noticing a time wasting trend here.. you keep adding new circumstances after the previous solution. Perhaps providing the entire set of circumstances in your original post would be better, as this saves people time from having to constantly refine solutions... otherwise, in theory, you can keep creating new requests one after the other, which could all have been solved earlier on.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.