Jump to content

How to "skip over words" in between other data


dsaba

Recommended Posts

Here is the sample haystack:

hi my a name b is

 

I want to match the string "hi my name is" without the 'b' and the 'a'

I know how to skip over words, or not match them when they come on the ends of strings, but not when they come in the middle of the string.

 

ie these two examples skip over the 'a'

~hi my name is (?=a)~ in  "hi my name is a"

~(?<=a) hi my name is~  in "a hi my name is"

 

I'd like to see how this can be done, or if it can be done at all with the PCRE engine in PHP.

Thanks

Link to comment
Share on other sites

<pre>
<?php
preg_match('/\A((??!\ba\b).)+)a((??!\bb\b).)+)b(.*)\z/', 'hi my a name b is', $matches);
print_r($matches);
array_shift($matches);
foreach ($matches as &$match) {
	$match = trim($match);
}
echo implode(' ', $matches);
?>
</pre>

Link to comment
Share on other sites

In that case I could have just used ~(hi my )a( name )b( is)~

instead of your pattern, because it yields the same results.

 

I wanted to see if this string alone could be the full match "hi my name is"

In your regex pattern, the full match is "hi a my name b is", so you didn't "skip" over any words, and the reason for the output is because of php code, not regex.

 

The two example matches I provided were quite easy, but in my question of only matching "hi my name is" in that haystack...this boggled my mind.

I didn't know if this could be done, so I take it you can't do it then?

Link to comment
Share on other sites

In that case I could have just used ~(hi my )a( name )b( is)~

instead of your pattern, because it yields the same results.

 

Your pattern assumes that it knows the content, which defeats the purpose of using a pattern at all, whereas mine only assumes that you know the words you want to skip.

 

In your regex pattern, the full match is "hi a my name b is", so you didn't "skip" over any words

 

The keyword here is "full." According to the documentation "$matches[0] will contain the text that matched the full pattern," and this is inescapable, as manixrock touched on.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.