Jump to content

Repeated Result Using Preg_Match And Negative Lookahead


lcp

Recommended Posts

I am trying to match only the word "handle" in this Tweet:

@testing50037393 @handle 123456 #checkin

 

I am using this regex expression - (?!testing50037393|checkin|\b\d)(\b\w+)

 

I am getting two results of the string "handle" as an array instead of just "handle" once. Please tell me how I can stucture this query to just get one instance of "handle".

 

I am getting this result with preg_match -

Array

(

[0] => handle

[1] => handle

)

 

And this with preg_match_all -

 

Array

(

[0] => Array

(

[0] => handle

)

 

[1] => Array

(

[0] => handle

)

 

)

 

Thanks,

Lela

So you understand, this is perfectly normal behavior: [0] is the entire string matched and [1] is what was captured by the first set of parentheses (first set that captures, that is).

 

The [1] is coming from the (\b\w+). Just remove the parentheses.

  • 2 weeks later...

To be clear, there is no way to have a single string returned with the preg_xxx functions, because that's not how they work. There's nothing particularly magical or mysterious about using $result[1] vs. $result (as a string), but if you insist, you will have to do something like $result = $result[1]; after the preg_xxx call. 

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.