mario millions mario millions - 1 month ago 18
PHP Question

RegEx Return part of a String

I have a list of musicians and songs in a single string that i need seperated. Each string contains a dash (-); however the artist name may also include a dash (-).

Examples

Lil Wayne - Drop It Like Its Hot
T-Pain - Bring the Heat


How do i write two regular expressions to

1) Return text before the furthest dash (-)
2) Return text after the furthest dash (-)

Answer

Mario, you can use the built-in regex function preg_split to split the entry into an array first:

$artist = "Lil Wayne - Drop It Like Its Hot";
$keywords = preg_split("/\-+/", $artist);

Once you have the array, you can re-assemble the content based on the requirements:

1) Return text before furthest dash (-)

$name = "";
for($x = 0; $x < count($keywords); $x++) {
     $name += $x;
} 

2) Return text after the furthest dash (-)

$arrlength = count($keywords)
$description = $keywords[$arrlength]
Comments