I am trying to build an array value of every item in my string that has <p>
tags around it (opening and closing ofcourse).
What I have now:
$info = $contentcr[0]['fulltext'];
preg_match_all('%^(<p[^>]*>.*?</p>)$%im', $info, $infoarray);
$splitinfo = preg_split('%^(<p[^>]*>.*?</p>)$%im', $info, -1, PREG_SPLIT_DELIM_CAPTURE);
When I print $splitinfo
somehow this is my array:
Array ( [0] =>
Afdeling: Bla & Bla
Locatie: ‘Stadhuis Rotterdam’ – Coolsingel 40 Rotterdam
Klant: Ontwikkelings
[1] =>
Bedrijf: Rotterdam Datum April 2013
[2] => )
This is what my string ($info
) looks like:
<p>Afdeling: Bla & Bla </p>
<p>Locatie: ‘Stadhuis Rotterdam’ – Coolsingel 40 Rotterdam</p>
<p>Klant: Ontwikkelings</p>
<p>Bedrijf: Rotterdam Datum April 2013</p>
How can I create every single paragraph as individual array values?
Using the following regex:
preg_match_all('@<p[^>]*>(.*?)</p>@im', $info, $infoarray);
it will match any <p></p>
and select the inner content (non-greedy using (.*?)
). preg_match_all
writes all findings into a multi-dimensional array. The first index will contain complete matches, while the 2..N
will contain a list of groups that matched. In our case something like:
array(2) {
[0]=>
array(2) {
[0]=>
string(10) "<p>adf</p>"
[1]=>
string(9) "<p>xy</p>"
}
[1]=>
array(2) {
[0]=>
string(3) "adf"
[1]=>
string(2) "xy"
}
}
will be generated. We can now just select the second part:
if (count($infoarray) > 1) {
// yes we found paragraphs!
$paragraphs = $infoarray[1];
}
There is no need for an additional split.
you can use below
$info = $contentcr[0]['fulltext'];
$splitinfo = preg_split('/(<\s*p\s*\/?>)|(<\s*br\s*\/?>)|(\s\s+)|(<\s*\/p\s*\/?>)/', $info, -1, PREG_SPLIT_NO_EMPTY);