View Full Version : help splitting a string

02-03-2010, 11:32 PM
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

02-03-2010, 11:50 PM
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

02-03-2010, 11:56 PM
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

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

02-04-2010, 01: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:

[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);
$keywords_short .= $keywords_short[$i];
$keywords_short = $keywords_short[1];
echo $keywords_short;


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

$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.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum