How do I check if a string contains a specific word

0 votes

Consider:

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')?

Nov 26, 2020 in Python by anonymous
• 65,770 points
1,439 views

1 answer to this question.

0 votes

You can use the strpos() function which is used to find the occurrence of one string inside another one:

$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').

answered Nov 26, 2020 by Gitika
• 65,770 points

Related Questions In Python

0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12, 2019 in Python by Nymeria
• 3,560 points
11,287 views
0 votes
1 answer

How do I check if a list is empty?

You can try the following: if not a:   print("List ...READ MORE

answered Mar 14, 2019 in Python by SDeb
• 13,300 points
876 views
0 votes
1 answer

How do I check if a list is empty in python?

Hey @Vedant, that's pretty simple and straightforward: if ...READ MORE

answered May 28, 2019 in Python by Karthik
1,069 views
0 votes
1 answer

How to check if a string contains a substring in Bash?

string='My long string' if [[ $string == ...READ MORE

answered Nov 26, 2020 in Python by Gitika
• 65,770 points
1,383 views
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,070 views
0 votes
1 answer

Removing surrounding whitespace

Try the strip() function:  s = s.strip() If you ...READ MORE

answered May 4, 2018 in Python by Nietzsche's daemon
• 4,260 points
777 views
0 votes
1 answer

How do I check if a given Python string is a substring of another one?

Try using in like this: >>> x = 'hello' >>> y ...READ MORE

answered Nov 26, 2020 in Python by Gitika
• 65,770 points
748 views
0 votes
1 answer

How do I check if a string is a number (float)?

I'm not sure that anything much could ...READ MORE

answered Dec 2, 2020 in Python by Gitika
• 65,770 points
809 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP