Jump to content

[SOLVED] substr_replace question


Walker33

Recommended Posts

Hello again!  Not sure I'm even going about this in the right way.  Trying to delete characters from a string.  String could be any length, characters could be anywhere, characters will always be 3 digits, followed by a comma.  My code deletes everything following the variable, but I only want the variable $final3 deleted.

 

<?php
$final3 = 'R07';
$revokedrow = 'R11,S12,S13,A05,R07,A07,A10,S03';
$start = strpos($revokedrow, $final3); 
$newrevoked = substr_replace($revokedrow, '', $start, $start+2);
echo "this is the new revoked line: $newrevoked<br>";

//getting R11,S12,S13,A05, instead of what I want, which is R11,S12,S13,A05,A07,A10,S03

?>

 

Any help is, as always, greatly appreciated!

Link to comment
https://forums.phpfreaks.com/topic/163400-solved-substr_replace-question/
Share on other sites

<?php

$final3 = 'R07';

$revokedrow = 'R11,S12,S13,A05,R07,A07,A10,S03';

$codes = explode(',', $revokedrow);

// see if $final3 is supposed to be revoked
for ($x = 0; $x < count($codes); $x++)
{
if ($codes[$x] == $final3)
{
	unset($codes[$x]);
}
}

$newrevoked = implode(',', $codes);

echo "this is the new revoked line: $newrevoked<br>";

?>

Thanks!  both worked. 2nd one seems simpler.  Is there something else to consider in using mattal's instead of flyhoney's?  Something I may not be seeing?  Really appreciate the help.

Efficiency, the second example is easier, so I'd go with that one.

Sorry, one thing I didn't see right.  Your code(s) work fine so long as $final3 doesn't end the string, where there is no comma.  Reversing ."," to the front of $final3, of course, works fine unless $final3 occurs at the beginning of the string.  Any ideas? 

 

<?php 
$final3 = 'R07';
$revokedrow = 'R11,S12,S13,A05,R07,A07,A10,S03';

$newrow = str_replace($final3.",", "", $revokedrow);

?>

 

<?php 

$final3 = 'R07';
$revokedrow = 'R11,S12,S13,A05,R07,A07,A10,S03';

$newrow = str_replace($final3.",", "", $revokedrow);
if($newrow == $revokedrow) {
// Try a str replace without the comma.
$newrow = str_replace($final3, "", $revokedrow);
}
if($newrow == $revokedrow) {
// Is not in string.
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.