PHP code example of stk2k / xstring

1. Go to this page and download the library: Download stk2k/xstring library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

stk2k / xstring example snippets


use stk2k\xstring\xs;

// Length
echo xs::length('Hello');    // 5
echo xs::length('你好');    // 2

// Join
echo xs::join(',', [1,2,3]);    // 1,2,3

// Index of
echo xs::indexOf('Hello', 'e');    // 1

// Contains
echo xs::contains('Hello', 'ell');    // true

// Starts with
echo xs::startsWith('Hello', 'He');    // true

// Ends with
echo xs::endsWith('Hello', 'lo');    // true

// Substring
echo xs::substring('Hello', 1, 2);    // el

// Remove
echo xs::remove('Hello', 1, 2);    // Hlo

// Insert
echo xs::insert('Hello World!', 5, ',');    // Hello, World!

// To lower case
echo xs::toLower('Hello');    // hello

// To upper case
echo xs::toUpper('Hello');    // HELLO

// Trim left and right
echo xs::trim(' [Hello] ');    // [Hello]

// Trim left
echo xs::trimStart(' [Hello] ', ' [');    // Hello]

// Trim right
echo xs::trimEnd(' [Hello] ', ' ]');    // [Hello

// Replace
echo xs::replace('Hello, World!', 'o', 'e');    // Helle, Werld!

// Replace by regular expression
echo xs::replaceRegEx('Hello, World!', '/o/', 'e');    // Helle, Werld!

// method chain
echo xs::trim(' [Hello] ')->toLower()->remove(1,2);    // [hlo]

// format
//  - see more samples: https://github.com/stk2k/xstring-format
echo xs::format('Hello, {0}!', 'David');    // Hello, David!

// foreach
xs::each('Hello', function($c){
    echo $c . '.';    // H.e.l.l.o.
});

// match
echo xs::match('Hello, World!', '/lo/');                      // ["lo"]
echo xs::match('Foo123, Bar456, Foo789', '/Foo([0-9]+)/');    // ['Foo123','123']

use function stk2k\xstring\globals\s;

echo s('Hello');                // Hello
echo s('Hello')->length();      // 5
echo s('Hello')->toLower();     // hello

// foreach
foreach(s('Hello') as $c){
    echo $c . '.';    // H.e.l.l.o.
}


use stk2k\xstring\xStringArray;

$sa = new xStringArray(['a', 'b', 'c']);

echo count($sa);                // 3
foreach($sa as $i) echo $i;     // abc
echo $sa->join(',');            // a,b,c
echo $sa->get(1);               // b
echo $sa[1];                    // b
unset($sa[1]);
echo $sa;                       // {"0":"a","2":"c"}
$sa[1] = 'Foo';
echo $sa;                       // {"0":"a","2":"c","1":"Foo"}

use stk2k\xstring\xStringBuffer;

$b = new xStringBuffer('abc');
$c = new xStringBuffer('a,b,c');

echo $b->length();                  // 3
echo $c->length();                  // 5
foreach($b as $i) echo $i;          // abc
echo json_encode($c->split(','));   // ["a","b","c"]
echo json_encode($b->split());      // ["a","b","c"]
echo $b->append('d');               // abcd