有人知道得到以下结果的正则表达式吗?
Hello world, Another day to die. => Hello world
我正在尝试下面的表达式:
/^.*,/
但是结果是'Hello world!'
我想忽略最后一个字符(!)。有人能帮我一下吗?
问好。
使用正面展望:
/^.*?(?=,)/
使用例子:
preg_match('/^.*?(?=,)/', "Hello world, Another day to die.", $matches);
echo "Found: {$matches[0]}'n";
输出:Found: Hello world
除了@acdcjunior的回答之外,还有以下几个选项:
"/^.*?(?=,)/" // (full match)
"/^(.*?),/" // (get element 1 from result array)
"/^[^,]+/" // (full match, bonus points for matching full string if there is no comma)
explode(",",$input)[0] // PHP 5.4 or newer
array_shift(explode(",",$input)) // PHP 5.3 and older
substr($input,0,strpos($input,","))
有很多方法可以达到这个目的;)
这是另一个,
$str = 'Hello world, Another day to die';
preg_match('/[^,]+/', $str, $match);
使用如下:
/^['w's]+/
使用这个,它只检查字母:
/^[a-z]+ [a-z]+/i
或不带regex:
$res = split(",", $string, 2)[0];