Several ways to intercept and organize strings in php

user:visitors Date:2021-12-07 16:04:531177

In php code, string functions are the core part of PHP, and there are many types of functions for various string processing.

When we deal with strings, the most commonly used is string interception.

So what are the commonly used string interception methods in php code?

1.substr (string, start position, length), it can quickly intercept a fixed-length string from the specified number of digits.

<?php

$zifu ="wqtool.com";

echo substr($zifu,3);

echo substr($zifu,2,4);

echo substr($zifu,-3);

?>

The output results are:

Start intercepting the third digit of the string and return the remaining part ool.com

Start intercepting from the second digit and return the next 4 characters tool

The parameter is a negative number, when -3, the com is taken from the end

When Chinese appears in the string, because Chinese characters are two bytes and English only has one byte, garbled characters are prone to appear.

At this time we will need to open the extension=php_mbstring extension in php.ini

The usage of mb_substr is the same as substr.

<?php

echo mb_substr("Text content",2,1,"UTF-8");

?>

The output result is: within

Regardless of substr and mb_substr, the remaining part is returned from the specified number of digits, so how to return to the previous character in reverse?

code show as below:

<?php

$weishu=3;

echo mb_substr( "text content", 0, mb_strlen( "text content",'utf8' )-$weishu );

?>

mb_substr is intercepted from the 3rd bit to the back, so in order to intercept to the front, then the starting value must be set to 0, and then the number of characters in the specified string is calculated and the specified number of digits is subtracted to get the interception to the front Length up.

The above is to specify the number of digits to start interception. Can the specified characters be expanded to begin interception, how to achieve it?

code show as below:

<?php

echo substr("abcde",stripos( "abcde", "c" ));

echo substr("abcde",0,stripos( "abcde", "c" ));

?>

The above will output respectively: de, ab

The principle is also very simple. Use stripos to find the first occurrence of the specified character "c" in the abcde character, and then the specified string can be intercepted to the left or right.

The above are some common ways of processing string interception in PHP.

Popular articles
latest article