Jump to content

[SOLVED] Only echo 1 if


newbtophp

Recommended Posts

<?php

$file = "hello, I have a pet goat, i know its random, but who cares?";

if(preg_match('/goat/', $file)) {

echo "it contains goat fool!";

}

if(preg_match('/hello/', $file)) {

echo "it contains hello!";

}

if(preg_match('/random/', $file)) {

echo "it contains random!";

}

?>

 

 

It would echo all of them, how would i only allow it to echo the first match (like in this case 'hello')

You could change the echos to die()'s, but this might not be practical if you have more code that will execute:

 

$file = "hello, I have a pet goat, i know its random, but who cares?";

if(preg_match('/goat'/, $file)) {

die("it contains goat fool!");

}

if(preg_match('/hello'/, $file)) {

die("it contains hello!");

}

if(preg_match('/random'/, $file)) {

die("it contains random!");

}

 

 

If you need to execute more code, you can make it into a function for parsing the file:

 

function parseFile($file)
{
if(preg_match('/goat'/, $file)) {

echo "it contains goat fool!";
return;
}

if(preg_match('/hello'/, $file)) {

echo "it contains hello!";
return;
}

if(preg_match('/random'/, $file)) {

echo "it contains random!";
return;

}
}

 

Then just call that function somewhere in your code.

 

Or you could use else if:

 

<?php

$file = "hello, I have a pet goat, i know its random, but who cares?";

if(preg_match('/goat/', $file)) {

echo "it contains goat fool!";

}

else if(preg_match('/hello/', $file)) {

echo "it contains hello!";

}

else if(preg_match('/random/', $file)) {

echo "it contains random!";

}

?>

You're not matching any patterns, no need for preg_match():

 

<?php
$file = "hello, I have a pet goat, i know its random, but who cares?";
$words = Array('goat', 'hello', 'random');
foreach($words as $word)
if(strpos($file, $word) !== false)
	echo 'Found ' . $word . '<br />';
?>

Oh sorry, I didn't realize that you wanted only one to echo.. Just add a break to my previous example (I can't edit it):

 

<?php
$file = "hello, I have a pet goat, i know its random, but who cares?";
$words = Array('goat', 'hello', 'random');
foreach($words as $word)
if(strpos($file, $word) !== false)
{
	echo 'Found ' . $word . '<br />';
	break;
}
?>

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.