A PHP CLI utility for finding and replacing text across files in a directory. Supports plain and regex-based replacements, case-insensitive matching, recursive directory scanning, extension filtering, and a dry-run preview mode.
- PHP 7.1+
php replaceText.php --find=TEXT --replace=TEXT [options]| Argument | Description |
|---|---|
--find=TEXT |
The text (or regex pattern) to search for |
--replace=TEXT |
The replacement text |
| Option | Description |
|---|---|
--dir=PATH |
Directory to scan (defaults to current working directory) |
--ext=php,js,txt |
Comma-separated list of file extensions to process |
--regex |
Treat --find as a regular expression |
--ignore-case |
Case-insensitive matching |
--recursive |
Scan subdirectories recursively |
--dry-run |
Preview changes without modifying any files |
Simple find and replace:
php replaceText.php --find="foo" --replace="bar"Case-insensitive, recursive, limited to PHP files:
php replaceText.php --find="foo" --replace="bar" --ignore-case --recursive --ext=phpRegex replace with a capture group:
php replaceText.php --find="/hello (\w+)/" --replace="hi $1" --regexPreview changes before applying them:
php replaceText.php --find="oldDomain.com" --replace="newDomain.com" --dir=./src --dry-runWhen using --regex, captured groups can be transformed using the ${transform:$N} syntax, where N is the capture group index.
| Transform | Description | Example input → output |
|---|---|---|
upper |
Uppercase | hello → HELLO |
lower |
Lowercase | HELLO → hello |
ucfirst |
Capitalise first letter | hello world → Hello world |
ucwords |
Capitalise each word | hello world → Hello World |
camel |
camelCase | hello_world → helloWorld |
snake |
snake_case | helloWorld → hello_world |
Example — convert snake_case function names to camelCase:
php replaceText.php \
--find="/function ([a-z_]+)\(/" \
--replace="function ${camel:$1}(" \
--regex --ext=php --recursiveEach modified file is reported with the number of replacements made:
UPDATED: /var/www/app/config.php (3 replacements)
UPDATED: /var/www/app/index.php (1 replacements)
------ Summary ------
Files scanned: 24
Files changed: 2
Replacements : 4
Mode: LIVE
In --dry-run mode, lines are prefixed with DRY RUN: and no files are written.