Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Find all occurrences of a substring in a string

Tags:

string

php

I need to parse an HTML document and to find all occurrences of string asdf in it.

I currently have the HTML loaded into a string variable. I would just like the character position so I can loop through the list to return some data after the string.

The strpos function only returns the first occurrence. How about returning all of them?

like image 751
muncherelli Avatar asked Apr 01 '13 03:04

muncherelli


People also ask

What is the use of strpos () function in PHP?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.

How do I search for a specific word in a string in PHP?

Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .

How will you locate a string within a string in PHP?

The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive.


2 Answers

Without using regex, something like this should work for returning the string positions:

$html = "dddasdfdddasdffff"; $needle = "asdf"; $lastPos = 0; $positions = array();  while (($lastPos = strpos($html, $needle, $lastPos))!== false) {     $positions[] = $lastPos;     $lastPos = $lastPos + strlen($needle); }  // Displays 3 and 10 foreach ($positions as $value) {     echo $value ."<br />"; } 
like image 147
Adam Plocher Avatar answered Sep 21 '22 19:09

Adam Plocher


You can call the strpos function repeatedly until a match is not found. You must specify the offset parameter.

Note: in the following example, the search continues from the next character instead of from the end of previous match. According to this function, aaaa contains three occurrences of the substring aa, not two.

function strpos_all($haystack, $needle) {     $offset = 0;     $allpos = array();     while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {         $offset   = $pos + 1;         $allpos[] = $pos;     }     return $allpos; } print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa")); 

Output:

Array (     [0] => 0     [1] => 1     [2] => 8     [3] => 9     [4] => 16     [5] => 17 ) 
like image 28
Salman A Avatar answered Sep 21 '22 19:09

Salman A