Currently I am using two foreach functions to put defined characters before and after a string (I use them as word separators - examples: " string.", " string ", "(string)" etc.). It looks like this: foreach(){ foreach(){ $needle = $separator . $string . $separator_end; preg_match($needle, $haystack); } } Code (markup): But this way of doing it isn't really effective. Do you have any idea how to put these separators (I store them in a database - they can be changed any time) to the regular expression to make it work?
Sure. .,?!:;'"`/()[]{}_+ =-<>~@#$%^&* Code (markup): The problem is that users may specify different separators, so I need to load them from a database - they must not be hardcoded.
Let me attempt to clarify your issue before I attempt a solution: You have a string: "same string, to be split" You want it to be split into an array by the comma: same string to be split However, you want to be able to do it with more than just the comma, but with any of the strings: .,?!:;'"`/()[]{}_+ =-<>~@#$%^&* Plus additional ones from the db. Is my analysis correct?
I don't need to add it to an array I just need to determine if a word with any combination of separators in my DB is present in a string. I am using 2 foreachs and preg_match to do that but I think that it can be done by using a single regexp without these loops. Any idea how to accomplish that?
Ok. I think I understand your question now. You want to know if any characters in string A exists in string B. // Match any of these chatacters $stringOne = '.,?!:;\'"`/()[]{}_+=-<>~@#$%^&*'; // Split by letter $stringOne = str_split($stringOne); $matchMe = ''; // Add | (OR) between the letters, quoting those characters needing quoting foreach ($stringOne as $string) { $matchMe .= preg_quote($string) . '|'; } // Remove last extra | character $matchMe = substr($matchMe, 0, -1); unset($stringOne); // Actual match $stringTwo = 'A string that might contain or not something from the above list in this case it does!'; if (preg_match('$' . $matchMe . '$', $stringTwo)) { echo 'match found'; } else { echo 'no match found'; } PHP: Hope this is what you are looking for.
Thank you. I replaced the preg_match function with the following row, it should be able to find words with separators now: preg_match('$(' . $matchMe. ')word('. $matchMe .')$', $stringTwo) Code (markup): I am just curious, why did you use the unset function? I know what it does but I really don't know why did you put it there.
You can call it a habit. I always unset variables that I do not need to use. Shouldn't make much difference on your side.