Page 1 of 1
split text into variables
Posted: Mon Feb 01, 2010 8:03 pm
by JKM
Hi there,
I'm having a string like this 'text text textblabla (<year>)' and I want to split it into $text, $year - but I'm not really sure how to do it.
Re: split text into variables
Posted: Mon Feb 01, 2010 9:15 pm
by JNettles
You can split a string of text into an array - you need to establish a consistent pattern to split by though. Example.....
Code: Select all
$string = "peter<~>lois<~>meg<~>chris<~>brian";
$split = explode("<~>", $string);
echo $split[0]; //outputs 'peter'
If you need something more complex than this I'd look into XML.
Re: split text into variables
Posted: Tue Feb 02, 2010 7:20 am
by JKM
Sorry, that won't do the trick - () can occur inside the text, so it should only fetch the text before (<year>) AND fetch the year without ().
Re: split text into variables
Posted: Tue Feb 02, 2010 8:19 am
by JNettles
How about you show the string you're actually wanting to split? Explaining your problem fully is the first key to getting help.
Re: split text into variables
Posted: Tue Feb 02, 2010 8:54 am
by JKM
It's IMDB titles,
- Pulp Fiction (1994) | $title = 'Pulp Fiction', $year = 1994
- 2001: A Space Odyssey (1968) | $title = '2001: A Space Odyssey', $year = 1968
- Lock, Stock and Two Smoking Barrels (1998) | $title = 'Lock, Stock and Two Smoking Barrels', $year = 1998
Re: split text into variables
Posted: Tue Feb 02, 2010 10:10 am
by JNettles
You can still use the example I posted - just use ( to split.
Re: split text into variables
Posted: Tue Feb 02, 2010 10:42 am
by JKM
What about for example
(500) Days of Summer?

Re: split text into variables
Posted: Tue Feb 02, 2010 10:57 am
by Grizzzzzzzzzz
Regular Expressions

Re: split text into variables
Posted: Tue Feb 02, 2010 11:04 am
by lshaw
preg_split("regex here",$srting);
You need to look into regular expressions and find out all the time your code needs to split. Someone please correct me if I have got the wrong funtion

Re: split text into variables
Posted: Tue Feb 02, 2010 11:20 am
by JNettles
Personal opinion but I tend to avoid regular expressions like death or marriage. They're slow, a pain to write, and can be easily broken the moment an odd string shows up. Again, my personal opinion but you'd probably be better off writing your own parsing routine using PHP's string functions if you can't get explode to work.
Re: split text into variables
Posted: Tue Feb 02, 2010 11:44 am
by JKM
I found another way to do it - how do I pick out only the year from a string? 'blablabla YYYY sadasd'