caramba
caramba

Reputation: 22490

explode string by last occurence of string in string return first and last part

Update: The $string can have one ore more ";". I have to look after the last one.

$string = "Hello world; This is a nice day; after";

$out[] = trim( substr( strrchr ($string, ";"), 1 ) );
$out[] = trim( substr( strrchr ($string, ";"), 0 ) );

var_dump($out);

result: array(2) { [0]=> string(3) "after" [1]=> string(5) "; after" }

but what I need is:

array(2) { [0]=> string(3) "after" [1]=> string(5) "Hello world; This is a nice day" }

How should I do it?

Upvotes: 1

Views: 508

Answers (5)

mim.
mim.

Reputation: 677

$string = "Hello world; This is a nice day; after";
/// Explode it
$exploded_string = explode(";", $string);
/// Get last element
$result['last_one'] = end($exploded_string);
/// Remove last element
array_pop($exploded_string);
/// Implode other ones
$result['previous_ones'] = implode(";", $exploded_string);

print_r($result);

Result will be:

Array ( [last_one] => after [previous_ones] => Hello world; This is a nice day ) 

Upvotes: 0

satdev86
satdev86

Reputation: 810

$string = "Hello world; This is a nice day; after";
$offset = strrpos($string,';');

$out[] = substr($string, $offset+1);
$out[] = trim(substr($string, 0, $offset));
print_r($out);

Upvotes: 0

hsz
hsz

Reputation: 152266

You can try with:

$string = "Hello world; This is a nice day; after";
$parts  = explode(';', $string);
$output = array(trim(array_pop($parts)), implode(';', $parts));

var_dump($output);

Output:

array (size=2)
  0 => string 'after' (length=5)
  1 => string 'Hello world; This is a nice day' (length=31)

Upvotes: 0

Chris J
Chris J

Reputation: 7769

$dlm = "; ";
$string = "Hello world; This is a nice day; after";

$split = explode($dlm,$string);
$last = array_pop($split);
$out = array($last,implode($dlm,$split));

Upvotes: 6

Nouphal.M
Nouphal.M

Reputation: 6344

Try

string = "Hello world; This is a nice day; after";
$out[] = trim(substr(strrchr($string, ";"), 1));
$out[] = trim(substr($string, 0, strrpos($string, ";")+1));

See demo here

Upvotes: 2

Related Questions