我有一个单独的字符串中的音乐家和歌曲列表,我需要分开。每个字符串都包含一个破折号( - );但艺术家名称也可能包含短划线( - )。
实施例
Lil Wayne - Drop It Like Its Hot
T-Pain - Bring the Heat
如何将两个正则表达式写入
1) Return text before the furthest dash (-)
2) Return text after the furthest dash (-)
答案 0 :(得分:0)
Mario,您可以使用内置的正则表达式函数preg_split
将条目首先拆分为数组:
$artist = "Lil Wayne - Drop It Like Its Hot";
$keywords = preg_split("/\-+/", $artist);
获得阵列后,您可以根据要求重新组合内容:
1)在最远的短划线( - )
之前返回文字$name = "";
for($x = 0; $x < count($keywords)-1; $x++) {
if ($x ==0) {
$name .= $keywords[$x];
} else {
$name = $name . "-" . $keywords[$x];
}
}
2)在最远的短划线( - )
之后返回文字$arrlength = count($keywords)
$description = $keywords[$arrlength-1]
答案 1 :(得分:-1)
您可以简单地使用explode()
功能。那么就没有必要使用Regex了。
$x = explode ("-", $string);
你将得到数组$ x。 $ x [0]将是第一部分,$ x [1]是第二部分。
修改强> 因此,对于“痛苦”来说你应该使用另一个分隔符:
$x = explode (" - ", $string);