PHP gets the nth occurrence of a character in a string and the position of the string

藏色散人
Release: 2023-04-07 22:06:01
forward
4098 people have browsed it

Because we often need to get part of the text in the string after fetching the source code of the web page, but I don’t know how to use regular expressions. The expressions I write often cannot get the desired content, so I wrote a function myself, which can basically get to the desired text.

Related recommendations: "PHP Tutorial"

1. Implementation function

/*
*取字符串中间文本
* @paramstring$str需要处理的字符串
* @paramstring $start_str 目标字符串‘前’的字符
* @paramstring $stop_str  目标字符串‘后’的字符
* @paramint $count     需要查找的次数
* @paramint $n   从第n个位置开始查找
* @returnarray$data返回查找满足条件要求的数组字符串
*/
function  get_msg($str,$start_str,$stop_str,$count,$n){
  $start=$n;  //从第n个位置开始查找
  $data=array();
  for($i=0;$i<$count;$i++){
$start=strpos($str,$start_str,$start);
$stop=strpos($str,$stop_str,$start);
$start=strlen($start_str)+$start;
$data[$i]= substr($str,$start,$stop-$start);
$start=$stop;
}
return $data;
  }
Copy after login

2. Implementation example

Copy after login

Return result

Array ( [0] => 这是一个字 ) 
Array ( [0] => 依然 [1] => 依然 [2] => )
Copy after login

Although there are three 'still' characters in the second string $strb, only two of them meet the conditions passed into the function, so only two that meet the conditions will be found.

Of course this is just a simple example, more complex strings can also be used, just pass in the corresponding conditions.

3. Search for the nth occurrence of characters and strings

This can be used in conjunction with the above function, depending on the requirements

/*查找字符、字符串第n次出现的位置
*@param string $str    原始字符串
*@param string $find需要查找的字符、字符串
*@param int    $n第几次出现的字符、字符串
*@return int   $count返回第n次出现的位置
*/
function str_n_pos($str,$find,$n){
        for ($i=1;$i<=$n;$i++){
            $pos = strpos($str,$find);
            $str = substr($str,$pos+1);
            $pos_val=$pos+$pos_val+1;
        }
$count = $pos_val-1;
        return $count; 
    }
Copy after login

The above is the detailed content of PHP gets the nth occurrence of a character in a string and the position of the string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!