PHP : Custom trim function instead existing ltrim() or rtrim()
I wonder if you did a quick Google search before rolling your own solution. Despite being implemented via different languages, they all give the same general regex solution.


Regex to remove all &lt;br /&gt; tags from beginning and end of a string in javascript
Remove &lt;br&gt; tags from the beginning and end of a string
Remove BR tag from the beginning and end of a string


As you have discovered, trim() functions treat the 2nd parameter as a "character mask", this means that it will greedily remove any consecutive characters from the beginning/end of the string from that "list of characters" (&lt;br&gt; is the same as rb&gt;&lt;).

If you need a utility function and require the same passed-in parameters:

function trimString($input, $find, $replacement = ' ', $type = 'ltrim') {
    $patterns = [
        'ltrim' =&gt; '^(?:' . preg_quote($find, '/') . ')+',
        'rtrim' =&gt; '(?:' . preg_quote($find, '/') . ')+$'
    ];
    $pattern = $patterns[$type] ?? implode('|', $patterns);
    return preg_replace('/' . $pattern . '/i', $replacement, $input);
}


If you want to be able to pass replacement strings which contain regex to the custom function like &lt;br\s*/?&gt;, then you can remove the preg_quote() calls entirely or set a flag/argument in the custim function which determines whether the quoting call should be implemented.  This means that the responsiblity of quoting any special characters is transferred from the custom function to whatever layer is calling the custom function.

If you want to use trim() before or after the execution of this custom function, that makes perfect sense too -- removing whitespace characters is exactly what it is mean to do.

If your requirements keep extending and you have the intention of removing HTML tags from a valid HTML document, then regex is probably not the right path to go down.  Regex is DOM-unaware and will be vulnerable to breakage in fringe case scenarios -- a legitimate DOM parser would be my strong recommendation in that case.