Jump to content

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 "/*".

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.