PHPackages                             torugo/tstring - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. torugo/tstring

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

torugo/tstring
==============

Toolset for validating and manipulating strings.

1.2.5(1y ago)0901MITPHPPHP &gt;=8.1

Since Jun 25Pushed 1y ago1 watchersCompare

[ Source](https://github.com/vitor-hugo/string-lib-php)[ Packagist](https://packagist.org/packages/torugo/tstring)[ RSS](/packages/torugo-tstring/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (12)Used By (1)

TString
========

[](#tstring-)

Small toolset for validating and handling strings.

Inspired on [validator.js](https://github.com/validatorjs/validator.js).

Table of Contents
==================

[](#table-of-contents-)

- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
    - [Via Traits](#via-traits)
    - [Via TString static object](#via-tstring-static-object)
- [Validators](#validators)
    - [contains](#contains)
    - [isAlpha](#isalpha)
    - [isAlphanumeric](#isalphanumeric)
    - [isBase64](#isbase64)
    - [isCnpj](#iscnpj)
    - [isCpf](#iscpf)
    - [IsEmail](#isemail)
    - [IsHexadecimal](#ishexadecimal)
    - [isLength](#islength)
    - [isNumeric](#isnumeric)
    - [isSemVer](#issemver)
    - [isUrl](#isurl)
        - [UrlOptions](#urloptions)
    - [maxLength](#maxlength)
    - [minLength](#minlength)
    - [maxVersion](#maxversion)
    - [minVersion](#minversion)
- [Handlers](#handlers)
    - [toString](#tostring)
    - [toLowerCase](#tolowercase)
    - [toTitleCase](#totitlecase)
    - [toUpperCase](#touppercase)
- [Contribute](#contribute)
- [License](#license)

Requirements
============

[](#requirements)

- PHP 8+
- PHP [mbstring extension](https://www.php.net/manual/en/mbstring.installation.php) installed and loaded.
- Composer 2+

Installation
============

[](#installation)

```
composer require torugo/tstring
```

Usage
=====

[](#usage)

You can use this library in two ways, using specific **Traits** or **instantiating the TString** class.

Via Traits
----------

[](#via-traits)

Traits are a good way to use only the functions you need, just use them within your classes.

Note

All valitors and manipulators traits functions visibility are `protected static`.

```
use Torugo\TString\Traits\Validators\TStringContains;

class MyClass()
{
    use TStringContains;

    public function myValidation() {
        // ...
        if (self::contains($haystack, $needle, false)) {
            // Do something...
        }
        // ...
    }
}
```

Via TString static object
-------------------------

[](#via-tstring-static-object)

TString class is the easiest way to use the functions of this library, by using it you will have access to all features in a single object.

```
use Torugo\TString\TString;

if  (TString::contains($haystack, $needle, false)) {
    // Do something
}
```

Validators
==========

[](#validators)

contains
--------

[](#contains)

Checks if a substring is contained in another string.

```
contains(string $haystack, string $needle, bool $caseSensitive = true): bool
```

Note

By default the case sensitiveness is enabled.

### Trait Namespace

[](#trait-namespace)

```
use Torugo\TString\Traits\Validators\TStringContains;
```

### Examples

[](#examples)

```
$text = 'The quick brown fox jumps over the lazy dog';

contains($text, 'fox jumps'); // returns true
contains($text, 'OVER', false); // returns true, case insensitive

contains($text, 'red fox'); // returns false
contains($text, 'LAZY DOG'); // returns false, case sensitive
```

isAlpha
-------

[](#isalpha)

Validates if a string have only alphabetical characters.

```
isAlpha(string $str, bool $includeUnicode = false): bool
```

Note

When enabled, the argument **`$includeUnicode`** will include some unicode alphabetic characters like accented letters, and alphabetical characters from some languages. This option is disabled by default.

### Trait Namespace

[](#trait-namespace-1)

```
use Torugo\TString\Traits\Validators\TStringIsAlpha;
```

### Examples

[](#examples-1)

```
isAlpha("abcdefghiklmnopqrstvxyzABCDEFGHIKLMNOPQRSTVXYZ"); // returns true
isAlpha("ãáàâäçéêëíïõóôöúüÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ", true); // returns true (unicode enabled)
isAlpha("ανάπτυξη", true); // returns true (unicode enabled)
isAlpha("発達", true); // returns true (unicode enabled)

isAlpha("Some text"); // returns false (no spaces)
isAlpha("ãáàâäçéêëíïõóôöúüÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ"); // returns false (unicode disabled)
isAlpha("지능"); // returns false (unicode disabled)
isAlpha("upplýsingaöflun"); // returns false (unicode disabled)
```

isAlphanumeric
--------------

[](#isalphanumeric)

Validates if a string have only alphanumeric characters.

```
isAlphanumeric(string $str, bool $includeUnicode = false): bool
```

Note

When enabled, the argument **`$includeUnicode`** will include some unicode alphabetic characters like accented letters, and alphabetical characters from some languages. This option is disabled by default.

### Trait Namespace

[](#trait-namespace-2)

```
use Torugo\TString\Traits\Validators\TStringIsAlphanumeric;
```

### Examples

[](#examples-2)

```
isAlphanumeric("abcdefghiklmnopqrstvxyzABCDEFGHIKLMNOPQRSTVXYZ0123456789"); // returns true
isAlphanumeric("twy5Z0V0lzhOItTa"); // returns true
isAlphanumeric("iZmáüàyÍsúL6DI00à0äúPÏvy", true); // returns true (unicode enabled)
isAlphanumeric("έτος2024", true); // returns true (unicode enabled)
isAlphanumeric("1983年は最高の年だ", true); // returns true (unicode enabled)

isAlphanumeric("march 1983"); // returns false
isAlphanumeric("13/03/1983"); // returns false
isAlphanumeric("έτος2024"); // returns false (unicode disabled)
isAlphanumeric("1983年は最高の年だ"); // returns false (unicode disabled)
```

isBase64
--------

[](#isbase64)

Validates whether a string is in Base64 format.
Also validates url safe Base64 strings.

```
protected static function isBase64(string $base64): bool;
```

### Trait Namespace

[](#trait-namespace-3)

```
use Torugo\TString\Traits\Validators\TStringIsBase64;
```

### Examples

[](#examples-3)

```
isBase64('THVrZSBJIGFtIHlvdXIgZmF0aGVyIQ=='); // returns true
isBase64('V2h5IHNvIHNlcmlvdXM/'); // returns true (url safe)
isBase64('VGhp/cy=BpcyBhIHRlc3Q'); // returns false
```

isCnpj
------

[](#iscnpj)

Validates if a given string has a valid CNPJ registration.

The Brazil National Registry of Legal Entities number (CNPJ) is a company identification number that must be obtained from the Department of Federal Revenue(Secretaria da Receita Federal do Brasil) prior to the start of any business activities.

```
protected static function isCnpj(string $cnpj): bool
```

### Trait Namespace

[](#trait-namespace-4)

```
use Torugo\TString\Traits\Validators\TStringIsCnpj;
```

### Examples

[](#examples-4)

```
isCnpj('60391682000132'); // returns true
isCnpj('99.453.669/0001-04'); // returns true, this is the default format
isCnpj('99 453 669 / 0001 (04)'); // returns true, it removes non numerical characters

isCnpj('99.453.669/0001-05'); // returns false, invalid verification digit
isCnpj('9953669000105'); // returns false, invalid length
isCnpj('999.453.669/0001-04'); // returns false, invalid length
```

Note

This validator uses a validation code from [Guilherme Sehn](https://gist.github.com/guisehn/3276302).

Important

The cnpj numbers above were generated randomly using [this tool](https://www.4devs.com.br/gerador_de_cnpj).
If one of them belongs to you, please send me a request to remove.

isCpf
-----

[](#iscpf)

Validates if a given string has a valid CPF identification.

CPF Stands for “Cadastro de Pessoas Físicas” or “Registry of Individuals”. It is similar to the “Social Security” number adopted in the US, and it is used as a type of universal identifier in Brazil.

```
protected static function isCpf(string $cpf): bool
```

### Trait Namespace

[](#trait-namespace-5)

```
use Torugo\TString\Traits\Validators\TStringIsCpf;
```

### Examples

[](#examples-5)

```
isCpf('88479747048'); // returns true
isCpf('532.625.750-54'); // returns true, this is the default format
isCpf('532 625 750 (54)'); // returns true, removes non numerical characters

isCpf('532.625.750-55'); // returns false, invalid verification digit
isCpf('53.625.750-54'); // returns false, invalid length
isCpf('532.625.750-541'); // returns false, invalid length
```

Note

This validator uses a validation code from [Rafael Neri](https://gist.github.com/rafael-neri/ab3e58803a08cb4def059fce4e3c0e40).

Important

The CPF numbers above were generated randomly using [this tool](https://www.4devs.com.br/gerador_de_cpf).
If one of them belongs to you, please send me a request and I will remove it immediately.

IsEmail
-------

[](#isemail)

Validates if a string has a valid email structure.

```
isEmail(string $email): bool
```

### Trait Namespace

[](#trait-namespace-6)

```
use Torugo\TString\Traits\Validators\TStringIsEmail;
```

### Examples

[](#examples-6)

```
// RETURNS TRUE
isEmail('foo@bar.com');
isEmail('x@x.com');
isEmail('foo@bar.com.br');
isEmail('foo+bar@bar.com');

// RETURNS FALSE
isEmail('invalidemail@');
isEmail('invalid.com');
isEmail('@invalid.com');
isEmail('foo@bar.com.');
```

Tip

Take a look at the [tests](./tests/Unit/Traits/Validators/IsEmailTest.php)to see more of valid or invalid e-mails.

IsHexadecimal
-------------

[](#ishexadecimal)

Validates if a string is a hexadecimal number.

```
isHexadecimal(string $hex): bool
```

### Trait Namespace

[](#trait-namespace-7)

```
use Torugo\TString\Traits\Validators\TStringIsHexadecimal;
```

### Examples

[](#examples-7)

```
isHexadecimal('c0627d4e8eae2e8e584d'); // returns true
isHexadecimal('1D5D98'); // returns true
isHexadecimal('0x4041E2F71BA5'); // returns true
isHexadecimal('0x15e1aea12b49'); // returns true

isHexadecimal('i0qh9o2pfm'); // returns false
isHexadecimal('#4EFCB7'); // returns false
isHexadecimal(' 4EFCB7 '); // returns false
isHexadecimal(''); // returns false
isHexadecimal('0X62F12E'); // returns true
```

isLength
--------

[](#islength)

Validates if the length of a string is between the minimum and maximum parameters.

```
isLength(string $str, int $min, int $max): bool
```

Important

If `$min` is negative it will be setted to `0` (zero).
If `$max` is lesser than `1` it will be setted to `1`.
If `$min` is lesser than `$max`, their values will be swapped.

### Trait Namespace

[](#trait-namespace-8)

```
use Torugo\TString\Traits\Validators\TStringIsNumeric;
```

### Examples

[](#examples-8)

```
isLength('MySuperStrongPassword!', 8, 64); // returns true
isLength('yágftÔúÍézÏP5mÕ3(8G}KQÖÜ', 24, 26); // returns true

isLength('fZ?ávãYów3j);ÜMK7!:k', 10, 20); // returns false, exceeded maximum length
isLength('xRh8É
