mario millions mario millions - 1 year ago 98
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 (-).


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 Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download