4

I'm searching a function to cut the following string and get all content BEFORE and AFTER

I need this part<!-- more -->and also this part

Result should be

$result[0] = "I need this part"
$result[1] = "and also this part"

Appreciate any help!

Chris
  • 4,255
  • 7
  • 42
  • 83

3 Answers3

10

Use the explode() function in PHP like this:

$string = "I need this part<!-- more -->and the other part.
$result = explode('<!-- more -->`, $string) // 1st = needle -> 2nd = string

Then you call your result:

echo $result[0]; // Echoes: I need that part
echo $result[1]; // Echoes: and the other part.
Frederick Marcoux
  • 2,195
  • 1
  • 26
  • 57
1

You can do this pretty easily with regular expressions. Somebody out there is probably crying for parsing HTML/XML with regular expressions, but without much context, I'm going to give you the best that I've got:

$data = 'I need this part<!-- more -->and also this part';

$result = array();
preg_match('/^(.+?)<!--.+?-->(.+)$/', $data, $result);

echo $result[1]; // I need this part
echo $result[2]; // and also this part

If you are parsing HTML, considering reading about parsing HTML in PHP.

Community
  • 1
  • 1
Joel Verhagen
  • 5,110
  • 4
  • 38
  • 47
1

Use preg_split. Maybe something like this:

<?php
$result = preg_split("/<!--.+?-->/", "I need this part<!-- more -->and also this part");
print_r($result);
?>

Outputs:

Array
(
    [0] => I need this part
    [1] => and also this part
)
adamdunson
  • 2,635
  • 1
  • 23
  • 27