Reputation: 491
I have 4 paragraphs of text in one string. Each paragraph is surrounded with <p></p>
.
I've searched on the web for anything already out there. There's quite a bit about displaying just the first paragraph, but nothing I could find about displaying paragraphs 1-2 and then the remaining paragraphs. Can anyone help here?
Not sure which to use if any, substr, strpos, etc.....?
EDIT - thanks for your answers, to clarify, the paragraphs don't contain HTML at the moment, but yes I will need the option to have HTML within each paragraph.
Upvotes: 0
Views: 2830
Reputation: 4736
Initialize with:
$dom = new DOMDocument;
$dom->loadHTML($myString);
$p = $dom->getElementsByTagName('p');
If each can contains other HTML elements(or not), create a function:
function getInner(DOMElement $node) {
$tmp = "";
foreach($node->childNodes as $c) {
$tmp .= $c->ownerDocument->saveXML($c);
}
return $tmp;
}
and then use that function when needing the paragraph like so:
$p1 = getInner($p->item(0));
You can read more about DOMDocument
here
Upvotes: 2
Reputation: 5253
Use regular expression:
$str = '<p style="color:red;"><b>asd</b>para<img src="afs"/>graph 1</p >
<p>paragraph 2</p>
<p>paragraph 3</p>
<p>paragraph 4</p>
';
// preg_match_all('/<p.*>([^\<]+)<\/p\s*>/i',$str,$matches);
//for inside html like a comment sais:
preg_match_all('/<p[^\>]*>(.*)<\/p\s*>/i',$str,$matches);
print_r($matches);
prints:
Array
(
[0] => Array
(
[0] => <p style="color:red;"><b>asd</b>para<img src="afs"/>graph 1</p >
[1] => <p>paragraph 2</p>
[2] => <p>paragraph 3</p>
[3] => <p>paragraph 4</p>
)
[1] => Array
(
[0] => <b>asd</b>para<img src="afs"/>graph 1
[1] => paragraph 2
[2] => paragraph 3
[3] => paragraph 4
)
)
Upvotes: 3