Extract a string from between 2 strings

In this article, I am going to show how to extract a string from between 2 strings. I will also be illustrating with an example, showing code samples and explanations.

Lets dive in …

The Example string

Below is the example string used for illustration in this article

$string = "10 = OPTION
	10 {
		text = Text to extract 1
	}
	20 = OPTION
	20 {
		text = Text to extract 2
	}
	30 = OPTION
	30 {
		text = Text to extract 3
	}
	40 = OPTION
	40 {
		text = Text to extract 4
	}";

I had a text like above and I wanted to extract all the strings found between the “text = ” and “}” characters and then use this extracted strings in a loop.

Below is the code and explanation of the code used to extract the strings.

$pattern = '/text = (.+)\s*\}/';
preg_match_all($pattern, $string, $matches);

foreach($matches[1] as $match) {
  echo $match;
}

Explanation

preg_match_all(): Finds all the matches of the specified pattern in the string being searched. Note that this is different from preg_match() which stops searching for other matches once a match has been found.

text = : This sub-pattern matches exactly the “text = ” characters in the string being searched.

(.+): “.+” matches one or more occurrences of any single character except a newline \n. Putting this in parenthesis like in (.+), makes any string which matches this first parenthesized sub-pattern to be added to the $matches[1] array. In our case, this is the string we want to extract.

\s*: Firstly, \s matches any white space character (space, tab, newline or carriage return character). So, \s* matches zero or more occurrences of any white space character.

\}: This matches the “}” character. The “}” character has a special meaning in Regular Expressions. That is why it was escaped using the “\” character so we could match exactly the “}” character.

$matches[1]: This is an array of strings which match the first pattern in the parenthesis “()“. If the pattern we used in the example above had another parenthesis after the first one, strings which match this pattern in the second parenthesis will be put into the $matches[2] array and so on.

To brush up on your basic RegExp knowledge, check out this great article.

Result from testing example code

Testing was done on PHP Live Regex.

Below is the screenshot showing the result of testing the pattern above with the example string above.

So, that was it for this article. Hope I was able to help.

If any questions, just let me know in the comments.

Leave a comment

Create a free website or blog at WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started