PHP Removing one letter from a long string only once?

I need to remove one character from a string, for example, in the text block below, I would need to remove ONE from j.

djriojnrwadoiaushd

care:

driojnrwadoiaushd

+1


a source to share


6 answers


You can also use str_relpace with the $ count parameter: $ str = 'djriojnrwadoiaushd'; echo str_replace ('j', '', $ str, 1);

Oops, sorry .. my bad.




Here's the real way:

$str = 'djriojnrwadoiaushd';
$pos = strpos( $str, 'j' );
if( $pos !== FALSE )
{
    echo substr_replace( $str, '', $pos, 1 );
}

      

+4


a source


Just use substrings:



<?php

$str = 'djriojnrwadoiaushd';
$remove = 'j';

$index = strpos($str, $remove);
if ($index !== false)
    $str = substr($str, 0, $index) . substr($str, $index + 1);

echo $str;

?>

      

+3


a source


Give it up - I know regular expressions;

$newString = preg_replace("/".preg_quote($stringToReplace)."/", '', $inputString, 1);

      

+2


a source


Try the following:

$needle = 'j';
if (($pos = strpos($str, $needle) !== false) {
    $str = substr($str, 0, $pos) . substr($str, $pos+strlen($needle));
}

      

+1


a source


strpos () returns the position of the first needle in the haystack i.e. the first j in your line. Then you just need to delete that letter.

0


a source


You can also take advantage of the fact that strings in PHP are arrays and remove the element corresponding to the 'j' value:

$str[strpos($str, 'j')] = null;

      

0


a source







All Articles