search

PHP strpos

Aug 29, 2024 pm 12:55 PM
php

The following article provides an outline for PHP strpos. There is a large set of built-in functions to make string related operations easier for the coder or the developer. The strops() is one of the popular string functions we can use as per requirements as its name suggests for dealing with the position in any string in PHP. Using this function, we can get the position of the string inside another string. This function can be used in various ways with various scenarios like we can get the first occurrence position of a string inside another. We can get the last occurrence position of the string inside another string. This function also can be used to search one string into another string.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of PHP strpos

Since this can be used in various ways, we can see the various syntax:

strpos($string, $toBeSearched)

Parameter Description:

  • $string: This is a string upon which the search needs to be done.
  • $toBeSearched: This is a string that needs to search inside the above string.

Return Type:

It returns the numeric value if the search finds it; otherwise it gives the false.

stripos($string, $toBeSearched, $startPostion)

We can see one additional parameter apart from the earlier one. $startPostion is nothing, but it’s all about where the search will be started.

strrpos($string, $toBeSearched, $startPostion)

This function can be used to search string into another string. This start was searching in the reverse order. The word ‘r’ in the middle of this function does the trick of searching the string into another string in the reverse order.

How does strpos() Function work in PHP?

  • To use the strpos() function and other related functions to it, we need to have two strings, one string will be searched into another string.
  • We have various other built-in functions like stripos(), strrpos(), strripos() etc. stripos() can be used to search the string of a case-insensitive search string. Strrpos() can be used to search the string in reverse order.
  • The strripos() can be used to search the sting in the reverse order of a case-insensitive search string.

Examples of PHP strpos()

Given below are the examples mentioned :

Example #1

A basic program using strops() function with only two parameters, string one and the search string.

Code:

<?php $string = "I love php, I love coding in php too!";
$searchString = "php";
$output =  strpos($string, $searchString);
echo "String:. “ $string;
echo "<br>Output: ". $output;
?>

Output:

PHP strpos

In the above example, we can see that in a string we are trying to search a PHP string, the use of strops() for searching the PHP word gives the output 7. 7 is the index of the first occurrence of the PHP word. The strops() is a case-sensitive function to find any string inside another string.

Example #2

Let’s try to replicate the same as in example 1 but with the PHP’s different case (upper or lower).

Code:

<?php $string = "I love php, I love coding in php too!";
$searchString = "PHP";
$output =  strpos($string, $searchString); // this will give the false result
echo "String: ". $string;
echo "<br>Output: ". $output;
$output1 =  stripos($string, $searchString); // this will give the the 7 as a result
echo "<br>String: ". $string;
echo "<br>Output: ". $output1;
?>

Output:

PHP strpos

In the above example, we can see that if the case if not matching in this case the strops() will not be doing the job, for this, we have stripos() with the same syntax and the parameter for doing the same job.

Example #3

Let’s see an example of using the third parameter as well with the strops().

Code:

<?php $string = "I love php, I love coding in php too!";
$searchString = "PHP";
$output =  strpos($string, $searchString,8); // this will give the false result
echo "String: ". $string;
echo "<br>Output: ". $output;
$output1 =  stripos($string, $searchString,8); // this will give the the 7 as a result
echo "<br>String: ". $string;
echo "<br>Output: ". $output1;
?>

Output:

PHP strpos

Just a little different from the previous example gives a huge difference as we can see in the result. We have put the 8 as a third parameter. Using 8 as a third parameter means the search will begin from position 8, not from position 0.

Example #4

Let’s see a bit of a professional example (handling types of return).

Code:

<?php $string = "https://www.educba.com/tutorials/?source=menu";
$searchString = "tutorials";
$output =  strpos($string, $searchString); // this will give the false result
if($output==false){
echo "Search not found.";
}else{
echo "Search found.";
}
?>

Output:

PHP strpos

Example #5

strrpos() can be used to search the position of the string into another string in the reverse order.

Code:

<?php $string = "I love PHP; I like to code in PHP";
$searchString = "PHP";
$output =  strrpos($string, $searchString); // this will give the false result
if($output==false){
echo "Search not found.";
}else{
echo "Search found: ".$output;
}
?>

Output:

PHP strpos

The same way, we can search the string into another of case-insensitive search string using the strripos() function. Now, we have seen the example of all the types of strops() we can use per the business requirements.

Conclusion

In PHP programming language, we can use the strpose() and the stripos() built-in functions to search a string into another. The strops() is a case-sensitive function to deal with the searching, and in PHP stripos() can be used for case-insensitive to do the same job like strops(). The stripos() don’t check for the same case. The developer must be careful enough while using these functions because if the searches match, it gives the numeric as a result but in case no search is found, it returns false.

The above is the detailed content of PHP strpos. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)