Jump to content

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;
}
?>

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.