Chris
Chris

Reputation: 4364

Cutting a string at a special character in PHP

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!

Upvotes: 4

Views: 13220

Answers (3)

addiedx44
addiedx44

Reputation: 2743

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
)

Upvotes: 1

Joel Verhagen
Joel Verhagen

Reputation: 5282

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.

Upvotes: 1

Frederick Marcoux
Frederick Marcoux

Reputation: 2223

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.

Upvotes: 10

Related Questions