String interception is more commonly used in PHP development, and there are many requirements for interception, such as the operation of a URL link: http://www.baijunyao.com/index.php/Home/Index/article/aid/12
Sometimes we want to intercept the last slash '/' behind the number;
Sometimes we need to intercept the first slash '/' in front of the content to determine the user Input URL link without http:/, and so on;
There are many ways to intercept PHP's built-in functions in a string, simply write a few examples;
1 |
$str = ‘123/456/789/abc‘ ; |
You can do this by intercepting the contents of the first slash:
1 |
echo substr ( $str ,0, strpos ( $str , ‘/‘ )) |
Or
123 |
$array = explode ( ‘/‘ , $str ); echo $array [0]; // 输出 123 |
You can do this by intercepting the contents of the first slash:
12 |
echo substr ( $str , strpos ( $str , ‘/‘ )+1); //输出 456/789/abc |
To intercept the contents of the last slash, you can do the following:
1 |
echo trim( strrchr ( $str , ‘/‘ ), ‘/‘ ); |
Or if you know the number of slashes
123 |
$array = explode ( ‘/‘ , $str ); echo $array [3]; //输出 abc |
But if you don't know how many slashes there are? What if you want the middle of a second slash and a third slash?
The following I wrote this function can be easily resolved as above all problems;
123456789101112131415161718192021222324252627 |
/**
* 按符号截取字符串的指定部分
* @param string $str 需要截取的字符串
* @param string $sign 需要截取的符号
* @param int $number 如是正数以0为起点从左向右截 负数则从右向左截
* @return string 返回截取的内容
*/
function
cut_str(
$str
,
$sign
,
$number
){
$array
=
explode
(
$sign
,
$str
);
$length
=
count
(
$array
);
if
(
$number
<0){
$new_array
=
array_reverse
(
$array
);
$abs_number
=
abs
(
$number
);
if
(
$abs_number
>
$length
){
return
‘error‘
;
}
else
{
return
$new_array
[
$abs_number
-1];
}
}
else
{
if
(
$number
>=
$length
){
return
‘error‘
;
}
else
{
return $array
[
$number
];
}
}
}
|
Example:
1234 |
echo
cut_str(
$str
,
‘/‘
,0);
//输出 123
echo
cut_str(
$str
,
‘/‘
,2);
//输出 789
echo
cut_str(
$str
,
‘/‘
,-1);
//输出 abc
echo
cut_str(
$str
,
‘/‘
,-3);
//输出 456
|
How to use this function to intercept the specified part of the content is strong enough;
This article for Bai Jun Remote original article, reprinted without contact with me, but please specify from Bai Jun remote blog baijunyao.com
PHP intercepts the specified part of a string by symbol