Jump to content

[SOLVED] Returning which match was found


play_

Recommended Posts

from this code:

$var1 = "@";
$var2 = "*";
$var3 = "/*";


$string = "Hello  world  this /* should be  ok";

$found = preg_match("/(?:\\$var1|\\$var2|\\$var3)/", $string);
if($found) {
	echo $found;
}

 

it returns true, because it find /*.

 

But is there a way to tell which one it found?

like, how would i know if it found $var1 or $var2 or $var3?

Link to comment
https://forums.phpfreaks.com/topic/50001-solved-returning-which-match-was-found/
Share on other sites

<pre>
<?php
$string = "Hello  world  this /* should be  ok";
$matches = array('@', '*', '/*');
foreach ($matches as &$match) {
	$match = preg_quote($match, '/');
}
$pattern = join('|', $matches);
if (preg_match("/($pattern)/", $string, $findings)) {
	echo $found, '<br>';
	print_r($findings);
}
?>
</pre>

  • 2 weeks later...

Can you put your variables in an array?

 

<?php
function pq($text) { return preg_quote($text,'/');}

$vars = array('*','@','/*');
$string = "Hello  world  this /* should be  ok";

preg_match('/('.implode('|',array_map("pq",$vars)).')/',$string,$match);

echo "Found \"$match[1]\"!\n";

?>

 

If not, maybe something like this:

<?php

$var1 = "@";
$var2 = "*";
$var3 = "/*";

$string = "Hello  world  this /* should be  ok";

if (is_int(strpos($string,$var1))) {
echo "Found \$var1 in \$string.";
} elseif (is_int(strpos($string,$var2))) {
echo "Found \$var2 in \$string.";
} elseif (is_int(strpos($string,$var3))) {
echo "Found \$var3 in \$string.";
} else {
echo "Nothing matched.";
}
?>

Of course, "*" will match the string since it matches the asterisk in "/*".

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.