1

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?

3
  • And what about playing with explode() instead? Commented Mar 7, 2014 at 9:56
  • Tried explode() but the string can varry, there is at least one ";" but there can be more. I have to look after last ";" and can only explode there. @fedorqui you show me how to play? Commented Mar 7, 2014 at 9:58
  • so do explode(";",$out) and explode(" ",$out) Commented Mar 7, 2014 at 9:59

5 Answers 5

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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)

Comments

0
$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);

1 Comment

same as mine.but you are faster than me to post it.So i am deleting mine.
0
$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 ) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.