regex question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
global_erp_solution
Forum Commoner
Posts: 25
Joined: Sun Jul 08, 2012 6:47 am

regex question

Post by global_erp_solution »

I notice all regex in PHP begins with / character. Does this signal the beginning of line?

Code: Select all

preg_match('/abc 12(de)??/','xxxyyy abc 12de, gghh',$result);
var_export($result);
will yield array (0=>'abc 12',)

while

Code: Select all

preg_match('/abc 12(de)?/','xxxyyy abc 12de, gghh',$result);
var_export($result);
will yield array (0=>'abc 12', 1=>'de',)

why is this? the difference is just the additional question mark in the regex.
Last edited by global_erp_solution on Sat Jul 28, 2012 11:50 pm, edited 1 time in total.
User avatar
TildeHash
Forum Commoner
Posts: 43
Joined: Fri Jul 16, 2010 7:17 am
Location: Apple Valley, California

Re: regex question

Post by TildeHash »

global_erp_solution wrote:I notice all regex in PHP begins with / character. Does this signal the beginning of line?
No. It signifies the beginning of the regular expression. "^" signifies the beginning of a line and "$" signifies the end.
global_erp_solution wrote:

Code: Select all

preg_match('/abc 12(de)??/','xxxyyy abc 12de, gghh',$result);
var_export($result);
will yield array (0=>'abc 12',)

while

Code: Select all

preg_match('/abc 12(de)?/','xxxyyy abc 12de, gghh',$result);
var_export($result);
will yield array (0=>'abc 12', 1=>'th',)

why is this? the difference is just the additional question mark in the regex.
A question mark normally means "non-greedy", two question marks should never be needed. However, I don't see what you're trying to do with this regular expression. What output do you want?

By the way:

Code: Select all

preg_match('/abc 12(de)?/','xxxyyy abc 12de, gghh', $result);
var_export($result);
Gives me:
[text]array ( 0 => 'abc 12de', 1 => 'de', )[/text]
And the question mark isn't required at all, neither is the "(de)" in your first example.
global_erp_solution
Forum Commoner
Posts: 25
Joined: Sun Jul 08, 2012 6:47 am

Re: regex question

Post by global_erp_solution »

yes, it should be de. sorry for the mistake. editted the post
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Re: regex question

Post by Live24x7 »

this is the shortest and the sweetest php regex tutorial:
http://knowpapa.com/php-regex/
Post Reply