bit3 / string-builder
此包已被废弃,不再维护。未建议替代包。
PHP的StringBuilder实现,类似Java
2.0.0
2014-12-17 10:34 UTC
This package is not auto-updated.
Last update: 2022-02-01 12:42:53 UTC
README
 
StringBuilder在PHP中的优势在于提供可变的、面向对象的字符串,以及所有必要的字符串操作方法,遵循Java StringBuilder。
如何使用
基本用法
$stringBuilder = new StringBuilder(); $stringBuilder->append('Hello world!'); echo $stringBuilder;
与编码一起工作
// set encoding on initialisation $stringBuilder = new StringBuilder(null, 'ISO-8859-1'); // set encoding after initialisation (will not convert contents) $stringBuilder->setEncoding('ISO-8859-15'); // change encoding and convert contents $stringBuilder->changeEncoding('UTF-16');
检查内容
// string start with... if ($stringBuilder->startsWith('Hello')) { ... } // bool(true) // string ends with... if ($stringBuilder->endsWith('world!')) { ... } // bool(true) // string contains... if ($stringBuilder->contains('Hello')) { ... } // bool(true) // search substring from the beginning $pos = $stringBuilder->indexOf('o w'); // int(4) // search substring from the ending $pos = $stringBuilder->lastIndexOf('o w'); // int(4) // get a char from a specific position $char = $stringBuilder->charAt(6); // string("w") // get a substring $substring = $stringBuilder->substring(6, 10); // string("world") // get length of the current sequence $length = $stringBuilder->length(); // int(11)
操作内容
// append content $stringBuilder->append('The end is near!'); // string("Hello world!The end is near!") // insert content $stringBuilder->insert(12, ' I know: '); // string("Hello world! I know: The end is near!") // replace partial content $stringBuilder->replace(13, 14, 'You'); // string("Hello world! You know: The end is near!") // delete substring $stringBuilder->delete(13, 22); // string("Hello world! The end is near!") // delete single character $stringBuilder->deleteCharAt(11); // string("Hello world The end is near!") // limit the length of the string $stringBuilder->setLength(11); // string("Hello world") // extend string to a specific length $stringBuilder->setLength(14, '!'); // string("Hello world!!!") // trim contents $stringBuilder->trim('!'); // string("Hello world") $stringBuilder->trimLeft('He'); // string("llo world") $stringBuilder->trimRight('dl'); // string("llo wor") // reverse content $stringBuilder->reverse(); // string("row oll")