Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object orientated strings / numbers in PHP?

Tags:

oop

php

I was looking at Ruby and it has a very nice OO structure unlike PHP with C-like string functions. I was wondering if there is an extension which makes strings into objects so you could use them like this:

$str = "sometext";
echo "len:" . $str->length; //would print 'len: 8'
like image 456
Kristina Brooks Avatar asked Dec 12 '10 19:12

Kristina Brooks


3 Answers

Take a look at this...

http://code.google.com/p/php-string/downloads/detail?name=string.php&can=2&q=

The class supports the extensions mbstring and iconv, and the package PHP-UTF8. It chooses the best available function for each method In addition, it provides many new methods. Some of them are: substringBetween, splice, startWith, endsWith and squeeze. It is also possible to use PHP internal functions, or custom functions, to manipulate the string.

Sample Code:

<?php

include('string.php');

$str = new String('sometext');
echo $str->length; //prints 8
echo $str->getLength(); //prints 8

?>

I have never used this class before but by looking at its documentation it has some pretty interesting methods. capitalize, charAt, compareTo, contains, etc..

like image 138
Jose Vega Avatar answered Oct 13 '22 01:10

Jose Vega


I'm a bit late to the game, but I was looking for a library just like this and came across this question. After more investigation I found the brilliant danielstjules/Stringy at GitHub.

I've looked over the documentation and the source and it looks pretty damn solid. I'd recommend taking a look at if you want a PHP String Wrapper class to make string manipulation easier. Note that this code is not a PHP extension, meaning there is no native manipulation, it is simply a wrapper.

Stringy

A PHP string manipulation library with multibyte support. Compatible with PHP 5.3+, PHP 7, and HHVM.

A few examples:

s('Upper Camel-Case')->upperCamelize(); // 'UpperCamelCase'
s('What are your plans today?')->truncate(19, '...'); // 'What are your pl...'
s('foo & bar')->containsAll(['foo', 'bar']); // true
s('Ο συγγραφέας είπε')->countSubstr('α'); // 2
like image 24
OptimusCrime Avatar answered Oct 13 '22 01:10

OptimusCrime


If you wanted to you could create your own String wrapper class that has all the string based methods and calculated attributes that you could possibly want. Edit: In the same way that Java has wrapper classes for some data types.

like image 23
Alexio Avatar answered Oct 13 '22 00:10

Alexio