PHP's sql_regcase in TypeScript

How to use

Install via yarn add locutus and import: import { sql_regcase } from 'locutus/php/pcre/sql_regcase'.

Or with CommonJS: const { sql_regcase } = require('locutus/php/pcre/sql_regcase')

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
1sql_regcase('Foo - bar.')'[Ff][Oo][Oo] - [Bb][Aa][Rr].'

Dependencies

This function uses the following Locutus functions:

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

import { getPhpLocaleGroup } from '../_helpers/_phpRuntimeState.ts'
import type { PhpInput } from '../_helpers/_phpTypes.ts'
import { setlocale } from '../strings/setlocale.ts'

const isRecord = (value: PhpInput): value is { [key: string]: PhpInput } =>
typeof value === 'object' && value !== null && !Array.isArray(value)
const defaultUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const defaultLower = 'abcdefghijklmnopqrstuvwxyz'

export function sql_regcase(str: string): string {
// discuss at: https://locutus.io/php/sql_regcase/
// original by: Brett Zamir (https://brett-zamir.me)
// example 1: sql_regcase('Foo - bar.')
// returns 1: '[Ff][Oo][Oo] - [Bb][Aa][Rr].'

let upper = ''
let lower = ''
let pos = -1
let retStr = ''

setlocale('LC_ALL', 0)

const lcCtypeValue = getPhpLocaleGroup('LC_CTYPE', 'LC_CTYPE')
if (lcCtypeValue && isRecord(lcCtypeValue)) {
const upperValue = lcCtypeValue.upper
const lowerValue = lcCtypeValue.lower
upper = typeof upperValue === 'string' ? upperValue : defaultUpper
lower = typeof lowerValue === 'string' ? lowerValue : defaultLower
} else {
upper = defaultUpper
lower = defaultLower
}
if (!upper || !lower) {
return str
}

// @todo: Make this more readable
for (let i = 0; i < str.length; i++) {
if ((pos = upper.indexOf(str.charAt(i))) !== -1 || (pos = lower.indexOf(str.charAt(i))) !== -1) {
retStr += '[' + upper.charAt(pos) + lower.charAt(pos) + ']'
} else {
retStr += str.charAt(i)
}
}

return retStr
}

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 pcre functions


Star