String interception is more commonly used in PHP development;
And there are many kinds of demand for interception;
For example, the operation of a URL link: http://baijunyao.com/article/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;
$str=‘123/456/789/abc‘;
Phpcopy
You can do this by intercepting the contents of the first slash:
echo substr($str,0,strpos($str, ‘/‘))
Phpcopy
或者
$array=explode(‘/‘, $str);echo $array[0];// 输出 123
Phpcopy
You can do this by intercepting the contents of the first slash:
echo substr($str,strpos($str,‘/‘)+1);//输出 456/789/abc
Phpcopy
To intercept the contents of the last slash, you can do the following:
echo trim(strrchr($str, ‘/‘),‘/‘);
Phpcopy
或者如果知道斜杠的个数
$array=explode(‘/‘, $str);echo $array[3];//输出 abc
Phpcopy
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;
/** * The specified part of the string is intercepted by symbol * @param string $STR the strings to be intercepted * @param string $sign the symbol to be intercepted * @param int $number If positive number starts from left to right from 0 to the right Cut left * @return string to return the captured content */functionCut_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 ( Span class= "token variable" > $number >= $length {return Span class= "token string" > ' error ' }else{ return $array [ $number ]} }} /span>
Phpcopy
Example:
EchoCut_str($str,‘/‘,0);Output 123EchoCut_str($str,‘/‘,2);Output 789echo cut_str($str,'/',-1); Output ABCecho cut_str($str,'/',-3); Output 456
Phpcopy
How to use this function to intercept the specified part of the content is strong enough;
PHP intercepts the specified part of a string by symbol