PHP's explode in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.
Rosetta Stone: golang/Split · swift/split

How to use

Install via yarn add locutus and import: import { explode } from 'locutus/php/strings/explode'.

Or with CommonJS: const { explode } = require('locutus/php/strings/explode')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1explode(' ', 'Kevin van Zonneveld')[ 'Kevin', 'van', 'Zonneveld' ]

Here's what our current TypeScript equivalent to PHP's explode looks like.

import type { PhpAssoc, PhpRuntimeValue } from '../_helpers/_phpTypes.ts'

type ExplodeValue = PhpRuntimeValue
type KeyedValues = PhpAssoc<ExplodeValue>

export function explode(
...args: [string | boolean | null | undefined, string | KeyedValues | (() => ExplodeValue) | undefined, number?]
): string[] | false | { 0: string } | null {
// discuss at: https://locutus.io/php/explode/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// example 1: explode(' ', 'Kevin van Zonneveld')
// returns 1: [ 'Kevin', 'van', 'Zonneveld' ]

let [delimiterRaw, stringRaw, limit] = args
let delimiter = delimiterRaw
const string = stringRaw

if (args.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined') {
return null
}
if (delimiter === '' || delimiter === false || delimiter === null) {
return false
}
if (
typeof delimiter === 'function' ||
typeof delimiter === 'object' ||
typeof string === 'function' ||
typeof string === 'object'
) {
return {
0: '',
}
}
if (delimiter === true) {
delimiter = '1'
}

// Here we go...
const normalizedDelimiter = delimiter + ''
const normalizedString = string + ''

const s = normalizedString.split(normalizedDelimiter)

if (typeof limit === 'undefined') {
return s
}

// Support for limit
if (limit === 0) {
limit = 1
}

// Positive limit
if (limit > 0) {
if (limit >= s.length) {
return s
}
return s.slice(0, limit - 1).concat([s.slice(limit - 1).join(normalizedDelimiter)])
}

// Negative limit
if (-limit >= s.length) {
return []
}

s.splice(s.length + limit)
return s
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star