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.

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

4 Answers4

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
Naftali
  • 144,921
  • 39
  • 244
  • 303
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>
greg0ire
  • 22,714
  • 16
  • 72
  • 101
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • `substr()` and `strpos()` may be slower and why should he use it if with `explode()` he can achieve same result easier? :) –  Oct 18 '11 at 15:58
  • 2
    minor modification is to remove the magic number 4, and replace it with strlen(""). – Yousf Oct 18 '11 at 15:59
  • 1
    nice solution!!! I prefer this one, it does what its intended to do, and not exploding, imploding, etc... the code it's clear – Packet Tracer Oct 18 '11 at 15:59
0

using your code, appending this should do the job

unset($strArray[0]);

$str2 = implode('</p>', $strArray);
Packet Tracer
  • 3,884
  • 4
  • 26
  • 36
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

hakre
  • 193,403
  • 52
  • 435
  • 836