Basic PHP Programming Question:
Download Job Interview Questions and Answers PDF
How to Find a Substring from a Given String in PHP?
Answer:
To find a substring in a given string, you can use the strpos() function. If you call strpos($haystack, $needle), it will try to find the position of the first occurrence of the $needle string in the $haystack string. If found, it will return a non-negative integer represents the position of $needle. Othewise, it will return a Boolean false. Here is a PHP script example of strpos():
<?php
$haystack1 = "2349534134345globalguideline16504381640386488129";
$haystack2 = "globalguideline234953413434516504381640386488129";
$haystack3 = "guideline234953413434516504381640386488129ggl";
$pos1 = strpos($haystack1, "globalguideline");
$pos2 = strpos($haystack2, "globalguideline");
$pos3 = strpos($haystack3, "globalguideline");
print("pos1 = ($pos1); type is " . gettype($pos1) . " ");
print("pos2 = ($pos2); type is " . gettype($pos2) . " ");
print("pos3 = ($pos3); type is " . gettype($pos3) . " ");
?>
This script will print:
pos1 = (13); type is integer
pos2 = (0); type is integer
pos3 = (); type is boolean
"pos3" shows strpos() can return a Boolean value
<?php
$haystack1 = "2349534134345globalguideline16504381640386488129";
$haystack2 = "globalguideline234953413434516504381640386488129";
$haystack3 = "guideline234953413434516504381640386488129ggl";
$pos1 = strpos($haystack1, "globalguideline");
$pos2 = strpos($haystack2, "globalguideline");
$pos3 = strpos($haystack3, "globalguideline");
print("pos1 = ($pos1); type is " . gettype($pos1) . " ");
print("pos2 = ($pos2); type is " . gettype($pos2) . " ");
print("pos3 = ($pos3); type is " . gettype($pos3) . " ");
?>
This script will print:
pos1 = (13); type is integer
pos2 = (0); type is integer
pos3 = (); type is boolean
"pos3" shows strpos() can return a Boolean value
Download PHP Interview Questions And Answers
PDF
Previous Question | Next Question |
How To Remove Leading and Trailing Spaces from User Input Values in PHP? | What Is the Best Way to Test the strpos() Return Value in PHP? |