Q:

Check if string contains a particular character in PHP

belongs to collection: PHP String Programs

0

The server side language PHP is quite popular in web industry because of its ability to create dynamic webpages and ease of learning curve for new developers. Working with strings in PHP is quite common because in web we mostly deal with web content and it is important to understand how to perform string operations.

In this article, we will check if any string contains a particular character or not. We will print to the webpage if it contains the character in the string otherwise not. Here's a PHP script to implement this functionality. We will be using strpos() function, which expects two parameter, one is string to check for any other is the character against which string has to find the character.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Code

<?php
	//We will get the email from form and store in email variable
	$email = $_POST['email'];

	//Inside if, we check using strpos function
	if (strpos($email, '@') !== false) {
		print 'There was @ in the e-mail address!';
	} else {
		print 'There was NO @ in the e-mail address!';
	}
?>

The return value from strpos() is the first position in the string at which the character was found. If the character wasn’t found at all in the string, strpos() returns false. If its first occurrence is found, it returns true.

In the if condition, we simply print to the page that the character was present if it is present and strpos returns true, otherwise, we print the character is not present.

If you like the article, share your thoughts in the comments below.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to convert a string to uppercase in PHP?... >>
<< How to convert array into string in PHP?...