How do I get the parts of string like: abc_abc\_cde_d ?

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

Moderator: General Moderators

Post Reply
nadavvin
Forum Commoner
Posts: 68
Joined: Wed Sep 06, 2006 6:05 am

How do I get the parts of string like: abc_abc\_cde_d ?

Post by nadavvin »

How do I get the parts of string like: abc_abc\_cde_d ?

The result should be: abc, abc\_cde, d
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

[feyd@home]>php -r "$t = 'abc_abc\_cde_d'; $n = preg_split('#(?<!\\\\)_#', $t); var_dump($n);"
array(3) {
  [0]=>
  string(3) "abc"
  [1]=>
  string(8) "abc\_cde"
  [2]=>
  string(1) "d"
}
nadavvin
Forum Commoner
Posts: 68
Joined: Wed Sep 06, 2006 6:05 am

Post by nadavvin »

Thanks
nadavvin
Forum Commoner
Posts: 68
Joined: Wed Sep 06, 2006 6:05 am

Post by nadavvin »

feyd wrote:

Code: Select all

$n = preg_split('#(?<!\\\\)_#', $t);

Can you explain how it's work?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

It looks for an underscore without a backslash before it. ... or are you asking me to break the entire pattern down?
nadavvin
Forum Commoner
Posts: 68
Joined: Wed Sep 06, 2006 6:05 am

Post by nadavvin »

to break the entire pattern down

Although, I know regular expression syntax, I don't know How this work.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

#(?<!\\\\)_#

# - opening delimiter
( - begin a group
?< - special command that for zero-width look behind
! - negate the zero-width; without this, it would require the enclosed pattern (of the group) before the pattern that follows the group.
\\\\ - A single backslash to PREG; PHP wants \\ to signal one backslash, so does PREG. To not escape the following closing parenthesis, we need four.
) - end the group
_ - underscore that's being looked for
# - ending delimiter
Post Reply