Skip to content

PHP string functions API

PHP's built-in string functions for measuring, searching, slicing, replacing and transforming strings.

1 class · 7 methods

string functions

7 methods

Procedural string functions provided by the PHP standard library.

strlen(string $string): int

Returns the length of the given string in bytes (not characters).

Parameters

NameTypeDescription
stringstringThe input string.

Returns

int

Example

php
<?php
echo strlen("hello");  // 5
echo strlen("日本語"); // 9 (UTF-8 bytes)
strpos(string $haystack, string $needle, int $offset = 0): int|false

Finds the numeric position of the first occurrence of needle in haystack. Returns false if not found.

Parameters

NameTypeDescription
haystackstringString to search in.
needlestringSubstring to find.
offsetintSearch starting offset (default 0).

Returns

int|false

Example

php
<?php
$pos = strpos("Hello, World", "World");
if ($pos !== false) {
    echo $pos;  // 7
}
substr(string $string, int $offset, ?int $length = null): string

Returns the portion of string specified by offset and length.

Parameters

NameTypeDescription
stringstringInput string.
offsetintStarting position (negative counts from end).
length?intMaximum length (null = to end).

Returns

string

Example

php
<?php
echo substr("Hello, World", 7);     // "World"
echo substr("Hello, World", 7, 3);  // "Wor"
echo substr("Hello", -3);           // "llo"
str_replace(array|string $search, array|string $replace, string|array $subject): string|array

Replaces all occurrences of search with replace in subject.

Parameters

NameTypeDescription
searcharray|stringValue(s) being searched for.
replacearray|stringReplacement value(s).
subjectstring|arrayString/array being searched.

Returns

string|array

Example

php
<?php
echo str_replace("world", "PHP", "hello world");  // "hello PHP"
echo str_replace(["a", "b"], "x", "abc");         // "xxc"
strtolower(string $string): string

Returns string with all ASCII alphabetic characters converted to lowercase.

Parameters

NameTypeDescription
stringstringInput string.

Returns

string

Example

php
<?php
echo strtolower("HELLO World");  // "hello world"
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

Splits a string by a separator and returns an array of the pieces.

Parameters

NameTypeDescription
separatorstringBoundary string.
stringstringInput string.
limitintMaximum number of elements.

Returns

array

Example

php
<?php
$parts = explode(",", "a,b,c");
// ["a", "b", "c"]
$parts2 = explode(",", "a,b,c", 2);
// ["a", "b,c"]
trim(string $string, string $characters = " \n\r\t\v\x00"): string

Strips whitespace (or other characters) from the beginning and end of a string.

Parameters

NameTypeDescription
stringstringInput string.
charactersstringOptional custom characters to strip.

Returns

string

Example

php
<?php
echo trim("  hello  ");        // "hello"
echo trim("---hi---", "-");    // "hi"