michaelmcgurk
michaelmcgurk

Reputation: 6509

Exploding strings in PHP

I have the following bit of PHP code.

Ultimately, I'd like to store <p>Michael is 26</p> in the $str1 variable and <p>He likes green cars.</p><p>And white footballs</p><p>And red lollies</p><p>And yellow suns</p> in the $str2 variable.

So basically everything in the first paragraph goes in $str1 and everything thereafter goes in $str2.

<?php
    $str = "<p>Michael is 26</p><p>He likes green cars.</p><p>And white footballs</p><p>And red lollies</p><p>And yellow suns</p>";
    $strArray = explode('</p>', $str);
    $str1 = $strArray[0] . '</p> ';
    echo $str1;
    // variable to export remainder of string (minus the $str1 value) ?
?>

How do I achieve this?

Many thanks for any pointers.

Upvotes: 3

Views: 188

Answers (4)

hakre
hakre

Reputation: 198117

You can use preg_splitDocs for this, unlike explode it allows to just look where to split. And it supports a limit as well:

list($str1, $str2) = preg_split('~(?<=</p>)~', $str, 2);

Demo

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270697

No explode() is necessary here. Simple string operations (strpos(), substr())will do fine:

$str = "<p>Michael is 26</p><p>He likes green cars.</p><p>And white footballs</p><p>And red lollies</p><p>And yellow suns</p>";
$str1 = substr($str, 0, strpos($str, "</p>") + strlen("</p>"));
$str2 = substr($str, strpos($str, "</p>") + strlen("</p>"));

echo $str1;
// <p>Michael is 26</p>
echo $str2;
// <p>He likes green cars.</p><p>And white footballs</p><p>And red lollies</p><p>And yellow suns</p>

Upvotes: 3

Packet Tracer
Packet Tracer

Reputation: 3924

using your code, appending this should do the job

unset($strArray[0]);

$str2 = implode('</p>', $strArray);

Upvotes: 0

Naftali
Naftali

Reputation: 146310

Use explode with a delimiter:

 explode('</p>', $str, 2);

This will return:

array (
   0 => '<p>Michael is 26',
   1 => '<p>He likes green cars.</p><p>And white footballs</p><p>And red lollies</p><p>And yellow suns</p>' 
)

So then all you have to do is:

$strArray = explode('</p>', $str, 2);
$str1 = $strArray[0] . '</p> ';
$str2 = $strArray[1];
echo $str1.$str2; //will output the original string again

Upvotes: 7

Related Questions