Home > Backend Development > PHP Tutorial > PHP获取一个字符串中间一部分字符的方法_php实例

PHP获取一个字符串中间一部分字符的方法_php实例

WBOY
Release: 2016-05-16 20:38:10
Original
1154 people have browsed it

这是一个获取字符串中两个子串之间的子串,如从字符串www.jb51.net中获取coderbolg子串,就让这个PHP函数来实现吧,代码如下:

复制代码 代码如下:

function get_between($input, $start, $end) {

  $substr = substr($input, strlen($start)+strpos($input, $start),

 (strlen($input) - strpos($input, $end))*(-1));

  return $substr;

}

$string = "www.jb51.net";

$start = "www.";

$end = ".net";

echo get_between($string, $start, $end);  // output:coderbolg


不过这个函数有个局限,就是$start子串和$end子串在整个串中只能出现一次。请看下面的例子:
复制代码 代码如下:

$string = "http://www.jb51.net/";

$start = "http://";

$end = "/";


很明显我想获取这个标准URL的域名部分,由于$end子串在整个串中不是唯一的,所以就会出现问题,请使用时务必注意!
Related labels:
source:php.cn
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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template