3

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.

4 Answers 4

7

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
Sign up to request clarification or add additional context in comments.

Comments

3

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>

3 Comments

substr() and strpos() may be slower and why should he use it if with explode() he can achieve same result easier? :)
minor modification is to remove the magic number 4, and replace it with strlen("</p>").
nice solution!!! I prefer this one, it does what its intended to do, and not exploding, imploding, etc... the code it's clear
0

using your code, appending this should do the job

unset($strArray[0]);

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.