Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cutting a string at a special character in PHP

Tags:

string

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!

like image 336
Chris Avatar asked Oct 27 '25 10:10

Chris


2 Answers

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.
like image 185
Frederick Marcoux Avatar answered Oct 28 '25 23:10

Frederick Marcoux


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.

like image 43
Joel Verhagen Avatar answered Oct 29 '25 00:10

Joel Verhagen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!