Search code examples
phpregexpreg-match

php regex preg wont match


PHP REGEX

// Search Field:
$e = "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'KM0403580-70' for key 'PRIMARY'"

// Code:
$errorRegex = ereg("\:.([0-9]+)[a-zA-Z\s]+'([A-Z]*)'$", $e, $moError);
echo $moError[2] . "  " . $moError[1];

Trying to get:

  1. 1062
  2. KM0403580-70

Any idea's what I'm doing wrong? I've been trying to find out for 4 hours now haha


Solution

  • This is probably the regex you are trying to write, although it will probably match a lot of things besides just your data...

    ^.*: ([0-9]+).* '([A-Z0-9-]+)'.*$
    

    Something like this would be much safer in that it would only find id codes from your specific type of error:

    ^SQLSTATE\[[0-9]+\]: Integrity constraint violation: ([0-9]+) Duplicate entry '([A-Z0-9-]+)' for key 'PRIMARY'$