0

Does anyone know what the regex to get the following result:

Hello world, Another day to die. => Hello world

I'm trying the following expression:

/^.*,/ 

But the result is 'Hello world!'

I want to ignore the last character (!). Can anyone give me a hand?

Best regards.

4

5 回答 5

4

使用积极的前瞻:

/^.*?(?=,)/ 

示例使用:

preg_match('/^.*?(?=,)/', "Hello world, Another day to die.", $matches);
echo "Found: {$matches[0]}\n";

输出:

Found: Hello world
于 2013-06-18T15:08:59.243 回答
0

除了@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,","))

有很多方法可以实现这一点;)

于 2013-06-18T15:11:42.243 回答
0

这是另一个,

$str = 'Hello world, Another day to die';
preg_match('/[^,]+/', $str, $match);
于 2013-06-18T15:12:21.677 回答
0

使用以下内容:

/^[\w\s]+/
于 2013-06-18T15:12:24.573 回答
0

使用这个,只检查字母:

/^[a-z]+ [a-z]+/i

或没有正则表达式:

$res = split(",", $string, 2)[0];
于 2013-06-18T17:08:32.130 回答