Extract multiple Strings between two String in PHP

Student

I am trying to make this work but I can't:

$str = "<html>1</html><html>2</html><html>3</html>";
$matches = array(); 
preg_match_all("(?<=<html>)(.*?)(?=</html>)", $str, $matches);

foreach ($matches as $d)
{
   echo $d;
}

What I am doing wrong? The output must be:

123
anubhava

This should work for you:

$str = "<html>1</html><html>2</html><html>3</html>";
preg_match_all("~(?<=<html>).*?(?=</html>)~", $str, $matches);

foreach ($matches[0] as $d) {
   echo $d;
}

Output:

123

Changes are:

  • Use missing regex delimiters ~ in preg_match_all function pattern
  • Remove capturing group since you are already using lookahead and lookbehind so entire match can be used in further processing
  • Using $matches[0] in foreach loop instead of $matches
  • There is no need to declare/initialize $matches before preg_match_all call

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

R - Extract String between two strings

Java Regex Extract String between two Strings

extract string between two strings of a cut result

Extract string between two strings in java

how to extract a string between two strings in R

Extract a string between two words, with multiple patterns

Extract data between two string with PHP

How to extract string between two slashes php

Get string between two strings [PHP]

PHP getting string in between two strings

Extract text between two strings repeating multiple times

Extract multiple strings between brackets or two different delimiters

How to extract multiple line strings between two keywords using grepwin

Pandas DataFrame - Extract string between two strings and include the first delimiter

Regular expression: extract string between two characters/strings

Python string extraction: Extract part between two predefined strings

Extract string between two strings using Regexp in Perl

Extract each string between each set of two different strings

extract string between two strings from text document using AppleScript

Regex: Extract string between two strings. No apparent delimitors

Extract text in between two strings if a sub-string present in between those two strings

Extract text in between two strings if a third string is also present in between those two strings- Pyspark

PHP: extract numbers between two strings using regex

Extract all strings between two other strings?

Extract strings between two strings using Regex

Script to extract strings between two strings in linux

Find string between strings and extract

Regex match multiple occurrences of a string between two strings

PHP Extract only a specific portion in a string between two characters