views:

675

answers:

6

I need to remove a single character from a string, eg in the text block below I would need to be able to remove ONE of the j's.

djriojnrwadoiaushd

leaving:

driojnrwadoiaushd

+1  A: 

Try this:

$needle = 'j';
if (($pos = strpos($str, $needle) !== false) {
    $str = substr($str, 0, $pos) . substr($str, $pos+strlen($needle));
}
Gumbo
A combination of this with mishac's answer would be neat.
Dominic Rodger
+2  A: 

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;

?>
Greg
A: 

strpos() returns the position of the first needle in the haystack, ie. the first j in your string. It's then quite simple to just remove that letter.

Berzemus
+1  A: 

Stand back - I know regular expressions;

$newString = preg_replace("/".preg_quote($stringToReplace)."/", '', $inputString, 1);
Visage
You should maybe consider calling preg_quote() on $stringToReplace otherwise you might get odd things happening, e.g. if $stringToReplace was .*
Tom Haigh
Very true. Thanks tom. Post edited to reflect that.
Visage
Using regular expressions for this task is like killing a fly with bazooka :D
Petrunov
A: 

You can also use the fact that strings in PHP are arrays, and remove the element corresponding to the 'j':

$str[strpos($str, 'j')] = null;
mishac
Interesting approach. If there is no j, however, this will probably try to remove the first letter.
thomasrutter
When being printed it displays a character firefox doesn't recognize, but for my purpose it works.
Sam152
This wouldn't work with multi-byte characters.
Gumbo
Are you just overwriting the j with a null rather than removing it? Sounds like you have to split the string and rejoin the beginning and the end leaving out the character you wish to remove.
Jay Dubya
+2  A: 

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

Ups, sorry.. my bad.


Here is a real way:

$str = 'djriojnrwadoiaushd';
$pos = strpos( $str, 'j' );
if( $pos !== FALSE )
{
    echo substr_replace( $str, '', $pos, 1 );
}
Petrunov
The last argument doesnt limit the number of replacements, it counts them.
bb