PHP's strrpos in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

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

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

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
1strrpos('Kevin van Zonneveld', 'e')16
2strrpos('somepage.com', '.', false)8
3strrpos('baa', 'a', 3)false
4strrpos('baa', 'a', 2)2

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

export function strrpos(haystack: string, needle: string, offset?: boolean | number): number | false {
// discuss at: https://locutus.io/php/strrpos/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// input by: saulius
// example 1: strrpos('Kevin van Zonneveld', 'e')
// returns 1: 16
// example 2: strrpos('somepage.com', '.', false)
// returns 2: 8
// example 3: strrpos('baa', 'a', 3)
// returns 3: false
// example 4: strrpos('baa', 'a', 2)
// returns 4: 2

let i = -1
if (typeof offset === 'number') {
i = (haystack + '').slice(offset).lastIndexOf(needle) // strrpos' offset indicates starting point of range till end,
// while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning
if (i !== -1) {
i += offset
}
} else {
i = (haystack + '').lastIndexOf(needle)
}
return i >= 0 ? i : false
}

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