I want to use preg_replace on a string, but although the string does not match, I get an empty string as return string.
PHP Code:
$sql = "k1 LIKE 'n' OR k2 LIKE 'n' OR k3 LIKE 'n' OR k4 LIKE 'n' OR k5 LIKE 'n' OR k6 LIKE '1' ";
print "SQL: $sql<br>";
$sql_A = preg_replace("/^([\w]+ LIKE\s?'?.*?'? OR )+ $/", "##$1##", $sql);
print "=> $sql_A<br>";
returns:
SQL: k1 LIKE 'n' OR k2 LIKE 'n' OR k3 LIKE 'n' OR k4 LIKE 'n' OR k5 LIKE 'n' OR k6 LIKE '1' =>
The weird thing is, the regex doesn't even match. I tried to simplify the string the most I could while getting the same result. I also might add an OR just before the end-$. But as soon as I drop some more or add sth. else, I get the normal behavior and the right replacement.
Does anyone see why this happenes? Maybe I made a mistake I'm not seeing, maybe this is a bug? I'm lost...
(Using PHP Version 5.3.21 on a LINUX Server)
--- 2013-04-24 21:30 ---
Edit:
If it helps, my originally used data was:
$sql = "SELECT count(*) AS anz FROM xxx_table LEFT JOIN yyy_table on yyy_table.devo=xxx_table.devo LEFT JOIN zzz_table ON (yyy_table.status=zzz_table.sid AND lang=1 AND yyy_table.for =zzz_table.for) LEFT JOIN kunde k on k.kd_nr = yyy_table.kd_nr LEFT JOIN locations l on l.lok_nr = yyy_table.lok_nr WHERE xxx_table.clear!='Y' AND xxx_table.ign!='Y' AND name NOT LIKE 'Container:%' AND name LIKE '%' AND event_prio LIKE '%' AND zzz_table.show='Y' AND ( k.ikd_nr LIKE '%n%' OR k.such LIKE '%n%' OR k.adr1 LIKE '%n%' OR k.adr2 LIKE '%n%' OR k.ort LIKE '%n%' OR k.strasse LIKE '%n%' )";
$sql_A = preg_replace("/(\((\s*[\w\.\-\`]+ (LIKE\s|=)\s*'?.+?'?\s*OR)* [\w\.\-\`]+ LIKE '%' (OR [\w\.\-\`]+ (LIKE\s|=)\s*'?.+?'?\s*)*\))/i", "", $sql);
And again, the result was NULL (not an empty string as I have learned ;) (Purpuse of this preg_replace is, to identify OR-conditions in SQL statements with LIKE '%' patterns to remove those unnecessary OR-conditions.)
If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.(php.net/manual/en/function.preg-replace.php) ... so there is probably an error with the pattern. The main one might be[\w]which should be\win PHP. There are a few more issues with the pattern though. What is the desired output?OR("OR" plus two spaces)?[\w]would be a problem. The[ ]is unnecessary, but I believe it's still functionally equivalent to simply\w.