Skip to content

Commit

Permalink
New: Add Carbon.String.replaceOnce
Browse files Browse the repository at this point in the history
  • Loading branch information
jonnitto committed Feb 6, 2024
1 parent 7361f5f commit 3db2043
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Classes/EelHelper/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,29 @@ public function convertCamelCase($string, $separator = '-'): string
);
}

/**
* Helper to replace the first occurrence of a string
*
* @param string $string The string being searched and replaced on
* @param string $search he value being searched for
* @param string|null $replace The replacement value that replaces found search value
* @return string
*/
public function replaceOnce(string $string, string $search, ?string $replace = null): string
{
$pos = strpos($string, $search);
if ($pos === false) {
return $string;
}

if (!isset($replace)) {
$replace = '';
}

return substr_replace($string, $replace, $pos, strlen($search));
}


/**
* Helper to make sure we got a string back
*
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,23 @@ Examples:

- `emailAddress` (string) The string to check

### `Carbon.String.replaceOnce(string, search, replace)`

Helper to replace the first occurrence of a string.

Examples:

| Expression | Result |
| ------------------------------------------------------ | ------------- |
| `Carbon.String.replaceOnce('Foo Bar Foo', 'Foo', 'X')` | `'X Bar Foo'` |
| `Carbon.String.replaceOnce('Foo Bar Foo', 'Foo ')` | `'Bar Foo'` |

- `string` (string) The string being searched and replaced on
- `search` (string) The value being searched for
- `prefix` (string, optional) The replacement value that replaces found search value

Returns the string with one occurrence replaced

## Number Helper

### `Carbon.Number.format(number, decimals, dec_point, thousands_sep)`
Expand Down

0 comments on commit 3db2043

Please sign in to comment.