Jump to content

match must have xyz and abc but in no particular order


msaspence

Recommended Posts

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

 

 

 

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

}

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...)/.

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

 

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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.