php 取出两个字符串的中间内容函数
时间: 2023-07-08 09:11:27 浏览: 60
你可以自定义一个函数来取出两个字符串的中间内容,具体实现如下:
```
function get_string_between($string, $start, $end) {
$start_pos = strpos($string, $start);
if ($start_pos === false) {
return "";
}
$start_pos += strlen($start);
$end_pos = strpos($string, $end, $start_pos);
if ($end_pos === false) {
return "";
}
return substr($string, $start_pos, $end_pos - $start_pos);
}
```
在这个函数中,$string 是原始字符串,$start 是目标子字符串的起始字符串,$end 是目标子字符串的结束字符串。函数首先使用 strpos 函数获取起始位置和结束位置,然后使用 substr 函数截取出目标子字符串。如果起始位置或结束位置不存在,则返回空字符串。
下面是一个示例代码,演示如何使用这个函数:
```
$string = "This is a sample string. Start of target string. End of target string. This is the end of the string.";
$startString = "Start of target string.";
$endString = "End of target string.";
$targetString = get_string_between($string, $startString, $endString);
echo $targetString;
```
输出结果为:
```
target string
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)