I've got the following string from an RSS feed... "Modern Scribe - Truly Successful (Original Mix) [Programmed Intelligence]" And I basically want to easily extract the parts enclosed in the different brakets and store them in a string. So I need the parts enslosed in () and [] brakets. Really, I basically want the "Modern Scribe", "Truly Successful" "Original Mix" and "Programmed Intelligence" extracted into strings so I can process them. How can this easily be done please people? Can't get preg_replace to make it happen Many thanks!
Use preg_match... (why would you use replace, only makes life a lot harder...) <?php $str = 'Modern Scribe - Truly Successful (Original Mix) [Programmed Intelligence]'; preg_match('/(?P<title>[^-]+)(?:\s+)?-(?:\s+)?(?P<info>[^\(]+)(?:\s+)?\((?P<mix>[^\)]+)\)(?:\s+)?\[(?P<label>[^\])]+)\]/i', $str, $matches); list(, $title, $info, $mix, $label) = array_map('trim', $matches); echo $title , ' - ' , $info , ' - ', $mix, ' - ', $label; PHP:
Sometimes people claim regular expressions are slow, here's an alternate relying heavily on strpos $string = "example (test1) [test2]"; $arr1 = array("(", ")", "[", "]"); foreach($arr1 as $value) { $a[] = strpos($string, $value); } $piece1 = substr($string, $a[0], $a[1]); $piece2 = substr($string, $a[2], $a[3]); PHP:
... and anyone who understands how php works is going to realize that version is going to take three or four times longer than a regex to execute since you are executing str_pos four times inside a loop, multiple array calls, substr twice (should be three times BTW), all of that control as php code which is inherently slower than the NATIVE code of a regex. substr is faster than a regex if you can get away with calling it only ONCE and only once for every time you call a regex without any overhead of calling a different function or an excess number of variables. Regex will kick substr's ass if you have to create an array, run four loop iterations of another function to put values into another array, to get to the point where you can call substr more than once... /FAIL/ Though at least you said CLAIM, which implies ignorance.