Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains a specific text [duplicate]

Tags:

php

<?php $a = '';  if($a exist 'some text')     echo 'text'; ?> 

Suppose I have the code above, how to write the statement "if($a exist 'some text')"?

like image 369
Lucas Fernandes Avatar asked Mar 08 '13 23:03

Lucas Fernandes


People also ask

How do I check if a string contains a specific word in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do I check if a string contains a word?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false . Also note that string positions start at 0, and not 1.

How do you check if a character is repeated in a string C#?

string repeatedWord = "woooooooow"; for (int i = 0; i < repeatedWord. Count(); i++) { if (repeatedWord[i] == repeatedWord[i+1]) { // .... } } The code works but it will always have an error because the last character [i + 1] is empty/null.


2 Answers

Use the strpos function: http://php.net/manual/en/function.strpos.php

$haystack = "foo bar baz"; $needle   = "bar";  if( strpos( $haystack, $needle ) !== false) {     echo "\"bar\" exists in the haystack variable"; } 

In your case:

if( strpos( $a, 'some text' ) !== false ) echo 'text'; 

Note that my use of the !== operator (instead of != false or == true or even just if( strpos( ... ) ) {) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos.

As of PHP 8.0.0 you can now use str_contains

<?php     if (str_contains('abc', '')) {         echo "Checking the existence of the empty string will always          return true";     } 
like image 103
Dai Avatar answered Oct 17 '22 01:10

Dai


Empty strings are falsey, so you can just write:

if ($a) {     echo 'text'; } 

Although if you're asking if a particular substring exists in that string, you can use strpos() to do that:

if (strpos($a, 'some text') !== false) {     echo 'text'; } 
like image 26
Blender Avatar answered Oct 17 '22 01:10

Blender