简体   繁体   中英

PHP regex remove specific part from end of string

I have the following string

"DJ Antoine, Conor Maynard - Dancing In The Headlights - teledysk, tekst piosenki"

and I would like to get only:

"DJ Antoine, Conor Maynard - Dancing In The Headlights"

I use regex but it not working:

^([^\;]+)$ - teledysk, tekst piosenki

Here is my two cents :

php > $s = "DJ Antoine, Conor Maynard - Dancing In The Headlights - teledysk, tekst piosenki";
php > $new_s = explode('-', $s, -1);
php > echo implode('-', $new_s);
DJ Antoine, Conor Maynard - Dancing In The Headlights 

Use preg_replace() to remove additional part of string. The regex select additional part and replace it with empty.

$str = preg_replace("/-[\w\s,]+$/", "", $str);

See result in demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM