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.

1
  • 2
    I didn't see any !. Commented Jun 18, 2013 at 15:10

5 Answers 5

5

Use a positive lookahead:

/^.*?(?=,)/ 

Example use:

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

Output:

Found: Hello world
Sign up to request clarification or add additional context in comments.

Comments

0

Along with @acdcjunior's answer, here are a few alternatives:

"/^.*?(?=,)/" // (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,","))

There are many ways to achieve this ;)

Comments

0

This is another one,

$str = 'Hello world, Another day to die';
preg_match('/[^,]+/', $str, $match);

Comments

0

Use the following :

/^[\w\s]+/

Comments

0

Use this, that only checks letters:

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

or without regex:

$res = split(",", $string, 2)[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.