PHP's preg_replace in TypeScript
How to use
Install via yarn add locutus and import:
import { preg_replace } from 'locutus/php/pcre/preg_replace'.
Or with CommonJS: const { preg_replace } = require('locutus/php/pcre/preg_replace')
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.
| # | code | expected result |
|---|---|---|
| 1 | preg_replace('/xmas/i', 'Christmas', 'It was the night before Xmas.') | "It was the night before Christmas." |
| 2 | preg_replace('/xmas/ig', 'Christmas', 'xMas: It was the night before Xmas.') | "Christmas: It was the night before Christmas." |
| 3 | preg_replace('\/(\\w+) (\\d+), (\\d+)\/i', '$11,$3', 'April 15, 2003') | "April1,2003" |
| 4 | preg_replace('/[^a-zA-Z0-9]+/', '', 'The Development of code . http://www.') | "TheDevelopmentofcodehttpwww" |
| 5 | preg_replace('/[^A-Za-z0-9_\\s]/', '', 'D"usseldorfer H"auptstrasse') | "Dusseldorfer Hauptstrasse" |
Here's what our current TypeScript equivalent to PHP's preg_replace looks like.
export function preg_replace(pattern: string, replacement: string, string: string): string { |
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
Star