PDA

View Full Version : help splitting a string



LJackson
02-04-2010, 12:32 AM
Hi All,

i am looking for some help please, im trying to split a string where a "-" is present and use everything after that and discard everything before

for example if i had

my first record - its my life

i want to grab just "its my life"

can anyone help please
many thanks
Luke

Fou-Lu
02-04-2010, 12:50 AM
Easiest way is just an explode:


$aPieces = explode('-', $string);
print $aPieces[1];

You'll need to confirm that the - exists with either a count (returns the number of pieces, 1 if no - present, two pieces if 1 - is present, etc).
There are other approaches of course, you can substring it based on a - itself. Personally, I'm lazy

LJackson
02-04-2010, 12:56 AM
Hi mate,

thanks for your help i appreciate it

i ended up chosing explode after looking at some alternatives and have the following code


$keywords = preg_replace("/:|\s*\(.*\)|\s*\[.*\]/U", "", $keywords);
$keywords_short = explode("-", $keywords);
$keywords_short = $keywords_short[1];

but when i print out $keywords_short; nothing prints out?
the $keywords has an - in it

any ideas
cheers
Luke

LJackson
02-04-2010, 01:08 AM
its ok solved it, relised that i had a sting replace function removing all - on another function thats why it wasnt working :)

thekooliest
02-04-2010, 02:54 AM
Just a note...
If you used this code:


$keywords = "test - some text - the rest of the text";
$keywords_short = explode("-", $keywords);
$keywords_short = $keywords_short[1];
echo $keywords_short;

The text:


some text

Would be echoed because your array looks like this:


Array
(
[0] => 'test '
[1] => ' some text '
[2] => ' the rest of the text'
)

In order to echo everything after the first hyphen you need to do something like this:


$keywords = "test - some text - the rest of the text";
$keywords_short = explode("-", $keywords);
$count = count($keywords_short);
for($i=1;$i<$count;$i++){
$keywords_short .= $keywords_short[$i];
$keywords_short = $keywords_short[1];
}
echo $keywords_short;


-Sam

SKDevelopment
02-04-2010, 10:50 AM
There are many ways to do this thing. Using explode() is a good way. Also you could do it using String functions:


<?php
$keywords = "test - some text - the rest of the text";
$position = strrpos($keywords,'-'); // position of the last occurrence
echo (false===$position)?$keywords:substr($keywords,$position+1);
?>

Probably the worst way would be to use regular expressions because regular expression functions are slower and take more resources.