Home » PHP

Check if string contains a particular character in PHP

In this article, we will learn how to find and check if string contains a particular character in PHP?
Submitted by Abhishek Pathak, on October 24, 2017

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.

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, '@') === true) {
		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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.