I needed to create a custom trim()
function instead of using existing ltrim or rtrim due to below problems.
Here are problem with existing functions.
$string = '<ul><li>This</li></ul>';
var_dump(ltrim($string, '<br>'));
// Output :: string(21) "ul><li>This</li></ul>"
As you can see ltrim trimming < brace because <br> not found I think (Not sure 100%).
Here created function,
function trimString($string, $replaceWith = ' ', $type = 'ltrim')
{
$type = (!empty($type) && in_array($type, ['ltrim', 'rtrim'])) ? $type : 'ltrim';
if (!empty($string) && !empty($replaceWith)) {
// Like ltrim
if ($type == 'ltrim') {
if (strpos($string, $replaceWith) === 0) {
$string = substr_replace($string, '', 0, strlen($replaceWith));
}
} elseif ($type == 'rtrim') {
// Like rtrim
$reverceString = strrev($string);
$replaceWithCount = strlen($replaceWith);
$count = 1;
for ($i = 0; $i < strlen($string); $i++){
if ($count <= $replaceWithCount) {
$newString .= $reverceString[$i];
}
$count++;
if ($count == $replaceWith) {
break;
}
}
if (!empty($newString)) {
if (strrev($newString) == $replaceWith) {
$string = strrev(strReplaceFirst($reverceString, strrev($replaceWith), ''));
}
}
}
}
return $string;
}
function strReplaceFirst($content, $from, $to)
{
if (!empty($content) && !empty($from)) {
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
return $content;
}
So, it is working properly for me! But I still don't know if it's the proper way to do that or not? Or it's side effect and time consumption.
ltrim
, you will understand why does it do what you saw. Second parameter is "character mask" it trims any of characters in that string. That means your call will trim anyb
,r
,<
and>
. \$\endgroup\$