Jump to content

Recommended Posts

Hi all.

I have been searching for this kind of match for quite some time. Also trying several things, but without any result.

 

I am trying to capture content between 2 words. In this case the 2 words are statis and the content between them is dynamic.

 

For example: My house number is 21 you know.

So i would like to capture the 21 in this case between "is" and "you".

 

Anybody who has any suggestion in this? Cause i just can't seem to figure this out for some reason.

Link to comment
https://forums.phpfreaks.com/topic/274447-preg_match-any-content-between-2-words/
Share on other sites

To match any static content in a regular expression, all you need to do is to write it as it appears in the string. To match anything in between, you need to use . (matches any character, except newlines by default) and a quantifier behind it. The most common ones are + (one, or more) and * (zero, or more), often with a question mark behind them to make them non-greedy.

The difference between greedy and non-greedy is that the non-greedy will stop at the first available match for what comes after the quantified group/character, while the greedy will match everything up to the last match. To give an example:

// Assume this baseline string:
"This is matching a character, or a string of characters."

// A non-greedy match for everything between "matching" and "character" would match this:
" a "

// A greedy, on the other hand would match this:
" a character, or a string of "

 

Putting all of this together, you'll end up with the following regular expression:

/is(.*?)you/

 

Learn more about regular expressions at Regular-Expressions.info.

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.