开发者

How to remove anything in a string after "-"?

开发者 https://www.devze.com 2023-02-04 06:46 出处:网络
This is the example of my string. $x = \"John Chio - Guy\"; $y = \"Kelly Chua - Woman\"; I need the pattern for the reg replace.

This is the example of my string.

$x = "John Chio - Guy";
$y = "Kelly Chua - Woman";

I need the pattern for the reg replace.

$pattern = ??
$x = preg_replac开发者_JS百科e($pattern, '', $x); 

Thanks


No need for regex. You can use explode:

$str = array_shift(explode('-', $str));

or substr and strpos:

$str = substr($str, 0, strpos($str, '-'));

Maybe in combination with trim to remove leading and trailing whitespaces.

Update: As @Mark points out this will fail if the part you want to get contains a -. It all depends on your possible input.

So assuming you want to remove everything after the last dash, you can use strrpos, which finds the last occurrence of a substring:

$str = substr($str, 0, strrpos($str, '-'));

So you see, there is no regular expression needed ;)


You could use strtok:

$x = strtok($x, '-');


To remove everything after the first hyphen you can use this regular expression in your code:

"/-.*$/"

To remove everything after the last hyphen you can use this regular expression:

"/-[^-]*$/"

http://ideone.com/gbLA9

You can also combine this with trimming whitespace from the end of the result:

"/\s*-[^-]*$/"


You can also use.

strstr( "John Chio - Guy", "-", true ) . '-';

The third parameter true tells the function to return everything before first occurrence of the second parameter.

Source on strstr() from php.net


I hope these patterns will help you =]

$pattern1='/.+(?=\s-)/'       //This will match the string before the " -";
$pattern2='/(?<=\s-\s).+/'    //This will match the string after the "- ";


Explode or regexp are an overkill, try this:

$str = substr($str, 0, strpos($str,'-'));

or the strtok version in one of the answers here.


Use the strstr function.

Example:

$my_string = "This is my best string - You like it?";
$my_new_string = strstr($my_string, '-', true);

echo($my_new_string);
0

精彩评论

暂无评论...
验证码 换一张
取 消