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
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>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

effigy, your example outputs:

 

Array ( [0] => /* [1] => /* )

which comes from "print_r($findings);".

$found doesn't seem to show anything =/

 

on php 5.2.1

 

 

As for obsidian and wildbug, those worked fine. thanks.

Link to comment
Share on other sites

Gotcha. $found must have been carried over from copying your code. There is no need for it once preg_match is placed inside an if construct. print_r was a generalization for example; I assumed you'd know how to dig into the array :)

Link to comment
Share on other sites

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.