Jump to content

preg_match any content between 2 words


crayhouse

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.

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.