lukaswhite / string-utilities
一些PHP的杂项字符串工具
1.0.0
2021-09-16 03:27 UTC
Requires (Dev)
- phpunit/php-code-coverage: ^9.2
- phpunit/phpunit: ^9.5
README
一些杂项PHP字符串工具。
删除标点符号
如名称所示,stripPunctuation()
方法从字符串中删除所有标点符号。
Strings::stripPunctuation( 'This, is a sentence, with - some - punctuation.' ); // outputs This is a sentence with some punctuation
为了避免替换破折号后出现的额外空格,请参阅
stripMultipleSpaces()
删除多个空格
stripMultipleSpaces()
删除多个空格
Strings::stripMultipleSpaces( 'This is a string that has some extra spaces' ); // outputs This is a string that has some extra spaces
替换子串的第n次出现
如果您有一个包含给定子串多次出现的字符串,但只想替换其中一个,请使用 replaceNth()
。
Strings::replaceNth( '0', '1', '0000000000', 5 ); // Outputs 0000100000
替换除第一次出现的所有子串
如果您有一个包含给定子串多次出现的字符串,但想替换所有除了第一次出现的子串,请使用 replaceAllButFirstOccurence()
。
Strings::replaceAllButFirstOccurence( '0', '1', '0000000000' ); // Outputs 0111111111
随机十六进制字符串
randomHex()
方法返回一个指定长度的随机十六进制数,作为字符串。
Strings::randomHex( 5 ); // Outputs something like de0f42
要强制它为大写,将 true
作为第二个参数传递。
Strings::randomHex( 5, true ); // Outputs something like DE0F42
以...开始
使用 startsWith()
来确定一个字符串是否以指定的子串开始。
Strings::startsWith( 'This is a test', 'This' ) // true
默认情况下,该方法区分大小写。要使其不区分大小写,请将 false
作为第三个参数传递。
Strings::startsWith( 'This is a test', 'this', false ) // true
以...结束
使用 endsWith()
来确定一个字符串是否以指定的子串结束。
Strings::startsWith( 'This is a test', 'test' ) // true
默认情况下,该方法区分大小写。要使其不区分大小写,请将 false
作为第三个参数传递。
Strings::startsWith( 'This is a test', 'Test', false ) // true
生成摘要
要生成摘要;也就是说,将字符串修剪到指定的最大单词数
$excerpt = Strings::excerpt( $content, 25 );
默认情况下,它将 ...
追加到字符串的末尾;可以通过可选的第三个参数更改此操作,例如
$excerpt = Strings::excerpt( $content, 100, '<a href="/path/to/page">Read More</a>' );
或者,如果您需要将摘要的长度限制为指定的字符数
$excerpt = Strings::excerptCharacters( $content, 200 );