msaspence Posted November 30, 2007 Share Posted November 30, 2007 how would i match a string that contains xyz and abc but in no particular order for example both aslkdjf abc kasjdfakj xyz adflkjadsf and aslkdjf xyz kasjdfakj abc adflkjadsf would match i know that in this example i could use | with both combinations but if i wanted to expand this to match xyz, abc, mno and qrs the number of combinations would be huge Quote Link to comment Share on other sites More sharing options...
mb81 Posted November 30, 2007 Share Posted November 30, 2007 My suggestion would be to create an array of the string segments you want to match it to, then search for each individually, then all of them have to evaluate true for it to be a valid string. A CRUDE ALGORITHM: HAYSTACKSTRING = "BLAH BLAH BLHA ABC XYZ" SEARCHSTRINGS = ARRAY ("ABC", "XYZ") GOODSTRING = TRUE FOREACH (SEARCHSTRING AS NEEDLESTRING) { IF ( NOT (NEEDLESTRING FOUND IN HAYSTACK STRING)) { GOODSTRING = FALSE } } IF (GOODSTRING) { WHATEVER YOU WANT TO DO TO IT } Quote Link to comment Share on other sites More sharing options...
effigy Posted November 30, 2007 Share Posted November 30, 2007 I think the pipe is your only option, short of running a bunch of strstrs. The advantage of using the pipe is the ability to condense similar strings. For example, if you were looking for "abc" and "abd" you would use /(?:ab[cd]|...more stuff...)/ rather than /(?:abc|abd|...more stuff...)/. Quote Link to comment Share on other sites More sharing options...
msaspence Posted November 30, 2007 Author Share Posted November 30, 2007 prehaps if i give a more precise example i want to find a certain tag with a cetain id, class and title so i might use /<div id="mydiv" class="myclass" title="mytitle".*>[^<]*</div> but this requires the id class and title attribute to be in a specified order which they might not nessassarily be Quote Link to comment Share on other sites More sharing options...
effigy Posted November 30, 2007 Share Posted November 30, 2007 See below. If you're doing a replace, you can use preg_replace_callback to analyze the attributes instead. <pre> <?php $data = <<<DATA ### Good <div id="mydiv" class="myclass" title="mytitle">data</div> <div title="mytitle" id="mydiv" class="myclass">data</div> <div class="myclass" title="mytitle" id="mydiv">data</div> ### Bad <div id="bob" class="myclass" title="mytitle">data</div> <div title="main" id="mydiv" class="myclass">data</div> <div class="math" title="mytitle" id="mydiv">data</div> DATA; preg_match_all('%<div\s+(??:class="myclass"|id="mydiv"|title="mytitle")\s*){3}>%', $data, $matches); foreach ($matches[0] as &$match) { $match = htmlspecialchars($match); } print_r($matches); ?> </pre> Quote Link to comment 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.