简体   繁体   English

用正则表达式删除字符串的末尾部分

[英]Remove with regex the end portion of a string

I'm trying to remove from a string everything start with / char, so if I have 我试图从字符串中删除一切以/ char开头,所以如果我有

my_value/j/im<b*+èo[/h>e\ylo

I'd like to remove the string /j/im<b*+èo[/h>e\\ylo and return only my_value . 我想删除字符串/j/im<b*+èo[/h>e\\ylo并仅返回my_value I thought to use something with str_replace but I'm not a great regex programmer and I'm doing practise with php. 我想用str_replace东西,但我不是一个伟大的正则表达式程序员,我正在用PHP练习。

function clean_value ($value) {
    return preg_replace ("^(/.*?)$", "", $value);
}

How can I do? 我能怎么做?

There is no reason to use regex here. 这里没有理由使用正则表达式。 Use a combo of strpos() and substr() instead: 使用strpos()substr()代替:

$original = 'my_value/j/im<b*+èo[/h>e\ylo';

$removed = substr($original, 0, strpos($original, '/'));

The above will work if you can guarantee that the string will always have at least 1 / character in it. 如果您可以保证字符串中始终至少包含1个/字符,则上述操作将起作用。 If you can't guarantee that or don't know, simply modify to: 如果您不能保证或不知道,只需修改为:

$removed = (strpos($original, '/') === false)
             ? $original 
             : substr($original, 0, strpos($original, '/'));

The simplest things can be done without regex 最简单的事情可以在没有正则表达式的情况下完成

$string = "my_value/j/im<b*+èo[/h>e\ylo";
$splitted = explode("/",$string,2);
echo  "$splitted[0]\n";

You forgot the delimiters in your regular expression. 你忘记了正则表达式中的分隔符 And ^/ requires the string to start with a / . 并且^/要求字符串以/开头。

Try this instead: 试试这个:

preg_replace("~/.*~", "", $value)

This will remove anything from the first / up to the end. 这将从第一删除任何/到最后。

You need to remove the starting caret from your regexp, and you can use a greedy match to get the rest of the string: 您需要从正则表达式中删除起始插入符,并且可以使用贪婪匹配来获取字符串的其余部分:

function clean_value ($value) {
    return preg_replace ("/\/.*/", "", $value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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