PHP mb_ereg_search_pos() Function
The mb_ereg_search_pos() is an inbuilt function in PHP that is used in regular expressions to match a given string. It searches for the first occurrence of a pattern in the string and returns the starting position and the ending position of the match.
Syntax:
mb_ereg_search_pos( ?string $pattern = null, ?string $options = null ): array|false
Parameters:
This function accepts 2 parameters that are described below:
- $pattern: This is the regular expression parameter that is used to search a pattern in the given string.
- $options: This is an optional parameter. That is used to specify matching options. It can be ‘m’ for multiline, the ‘^’ and ‘$’ anchors will match the beginning and end of each line in the input string.
Return Value:
The mb_ereg_search_pos() function returns an array that contains the position value of the first occurrence of the string. If the function successfully executes, it will return “true”, otherwise It will return “false”.
Program 1: The following program demonstrates the mb_ereg_search_pos() Function.
PHP
<?php $text = "Food is tasty. The sun is shining" ; $pattern = "The" ; // Set the multibyte encoding mb_regex_encoding( "UTF-8" ); // Initialize the search $bool = mb_ereg_search_init( $text ); if (mb_ereg_search_pos( $pattern )) { echo "Pattern is Found" ; } else { echo "Pattern is not found" ; } ?> |
Pattern is Found
Program 2: The following program demonstrates the mb_ereg_search_pos() Function.
PHP
<?php $text = "I love apples. Apples are delicious." ; $pattern = "apples" ; // Set the multibyte encoding mb_regex_encoding( "UTF-8" ); // Initialize the search $bool = mb_ereg_search_init( $text ); $array = mb_ereg_search_pos( "$pattern" ); // Return the postion number of pattern echo $array [1]; ?> |
6
Program 3: The following program demonstrates the mb_ereg_search_pos() function
PHP
<?php $text = "Hello, world! This is a sample text." ; $pattern = "world" ; // Set the multibyte encoding mb_regex_encoding( "UTF-8" ); // Initialize the search $bool = mb_ereg_search_init( $text ); // Find the position of the match $array = mb_ereg_search_pos( $pattern ); if ( $array !== false) { $start = $array [0]; $end = $array [1]; $matchedText = mb_substr( $text , $start , $end - $start ); echo "Match found:'$matchedText' at positions $start-$end.\n" ; } else { echo "No match found." ; } ?> |
Match found: 'world! This is a sample tex' at positions 7-5.
Reference: https://www.php.net/manual/en/function.mb-ereg-search-pos.php
Contact Us