dreamwest Posted November 30, 2009 Share Posted November 30, 2009 How can i use a variable within preg_match_all?? $img = "fun.jpg"; preg_match_all('~[\'"](.*?)".$img."[\'"]~is', $str, $a); Quote Link to comment https://forums.phpfreaks.com/topic/183484-use-variables-within-preg_match_all/ Share on other sites More sharing options...
salathe Posted November 30, 2009 Share Posted November 30, 2009 First, you're using the wrong type of quotation marks (double instead of single) in that snippet. Second, it is advisable to use preg_quote because the variable value might contain special characters (like yours contains the dot) which mean something in regular expressions. An example might be: $img = "fun.jpg"; preg_match_all('~[\'"](.*?)' . preg_quote($img, '~') . '[\'"]~is', $str, $a); I sometimes like to make things a little "neater" (arguably) using sprintf but it's purely cosmetic and does nothing different than the code above: $img = "fun.jpg"; $pattern = sprintf('~[\'"](.*?)%s[\'"]~is', preg_quote($img, '~')); preg_match_all($pattern, $str, $a); Quote Link to comment https://forums.phpfreaks.com/topic/183484-use-variables-within-preg_match_all/#findComment-968520 Share on other sites More sharing options...
dreamwest Posted December 1, 2009 Author Share Posted December 1, 2009 Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/183484-use-variables-within-preg_match_all/#findComment-968592 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.