0

How does know how I can make a PHP script that checks if a HTML code stored as a variable contain certain words?

To illustrate my problem:

$html = "<p>My name is Herman</p><br><span>I like to eat hamburgers</span>";

For example; I need a PHP script that can check if this variable contains "Herman" or "hamburger".

Thanks you :)

2 Answers2

2

Use strpos.

<?php
$html = "<p>My name is Herman</p><br><span>I like to eat hamburgers</span>";

if(strpos($html, "Herman") !== false) {
    echo "string found";
} else {
    echo "string not found";
}
?>
MikkoP
  • 4,864
  • 16
  • 58
  • 106
  • But if I want to check multiple words? (like "Herman" and "Hamburger" at the same time? Thanks :) – user2846191 Oct 23 '13 at 16:24
  • If you want to check if "Herman" or "hamburger" exists in the string, use `strpos($html, "Herman") !== false || strpos($html, "hamburger") !== false` Using `&&` instead of `||` returns true only if both words exist in the string. Otherwise, check this. http://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos – MikkoP Oct 23 '13 at 16:25
  • Isn't it a easier way to to it (like using an array)? :) – user2846191 Oct 23 '13 at 16:30
  • Did you check the link I sent you? – MikkoP Oct 23 '13 at 16:32
0

You should probably use function strtolower to make your search case insensitive, then use strpos. It will find the numeric position of the first occurrence of your search in the haystack string return 0 if not found.

$lowhtml=strtolower($html);
if((strpos($lowhtml, 'hamburger')!=false) && (strpos($lowhtml, 'herman')!=false)){
    echo "Contains";
}else{
    echo "Doesn't contain";
}
Ijon Tichy
  • 447
  • 2
  • 7
  • Indexing starts at zero, so your answer is invalid. The function returns false if the string was not found. Also, did the asker ask about case insensitive search? – MikkoP Oct 23 '13 at 16:31
  • Seems you edited your answer. You can't use `!= false`. Quote from the PHP docs: `This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.` – MikkoP Oct 23 '13 at 16:35
  • Yes I have. I wasn't quite sure how to communicate to you. Still getting used to the site. Thanks a lot for your corrections and sorry for wasting your time. – Ijon Tichy Oct 23 '13 at 16:38