danielstjules / sliceable-stringy
Python string slices in PHP
Installs: 51 602
Dependents: 1
Suggesters: 1
Security: 0
Stars: 48
Watchers: 5
Forks: 2
Open Issues: 1
Requires
- php: >=5.4.0
- danielstjules/stringy: 1.4.x
Requires (Dev)
This package is not auto-updated.
Last update: 2024-12-21 17:17:19 UTC
README
Python string slices in PHP. The class extends
Stringy, and implements the
ArrayAccess
interface.
Installation
If you're using Composer to manage dependencies, you can include the following in your composer.json file:
"require": {
"danielstjules/sliceable-stringy": "dev-master"
}
Then, after running composer update
or php composer.phar update
, you can
load the class using Composer's autoloader:
require 'vendor/autoload.php';
Overview
SliceableStringy
returns a slice when passed a string offset containing
one or more colons. Up to 3 arguments may be passed: 'start:stop:step'
.
Start, which indicates the starting index of the slice, defaults to the first
character in the string if step is positive, and the last character if negative.
Stop, which indicates the exclusive boundary of the range, defaults to the
length of the string if step is positive, and before the first character if
negative. And step allows the user to include only every nth character in the
result, with its sign determining the direction in which indices are sampled.
Just like Stringy
, SliceableStringy
is immutable and returns a new
instance with each slice.
Examples
use SliceableStringy\SliceableStringy as S; $sliceable = S::create('Fòô Bàř', 'UTF-8');
Specific offset
$sliceable[1]; // 'ò' $sliceable['-2']; // 'à'
Using start and stop
$sliceable[':']; // 'Fòô Bàř' $sliceable['4:']; // 'Bàř' $sliceable['4:6']; // 'Bà'
Negative indices
$sliceable['-1:']; // 'ř' $sliceable[':-1']; // 'Fòô Bà' $sliceable['-3:6']; // 'Bà' $sliceable['2:-6']; // ''
Passing a step
$sliceable['::-1']; // 'řàB ôòF' $sliceable['::2']; // 'FôBř' $sliceable['-3::-2']; // 'BôF'
Possible exceptions
$sliceable[20]; // OutOfBoundsException $sliceable['1:2:3:4']; // InvalidArgumentException, too many slice args $sliceable['::0']; // InvalidArgumentException, step cannot equal 0
Implementation Fidelity
A number of specs in spec/SliceableStringySpec.php
assert that the library
mimics Python's native slice notation. On top of the handful of unit tests,
spec/fixtures/resultGenerator.py
has been used to generate test fixtures.
Each of the slices in expectedResults.csv
are checked against SliceableStringy
to ensure correct functionality.
TL;DR
Butchering two languages with a single library.