XK8ER
asked on
use preg replace to remove last digit
hello there,
if there is a back slash in the last digit of a string like this
A Christmas Carol \
how can I remove it and just end up like this
A Christmas Carol
if there is a back slash in the last digit of a string like this
A Christmas Carol \
how can I remove it and just end up like this
A Christmas Carol
$string = preg_replace("@\\$@","",$s tring);
I think you can use rtrim function to remove last backslash character at the end of string.
Example :
Example :
$text = 'A Christmas Carol \';
$new_text = rtrim($text, '\');
//new_text now does not contain a back slash at the end of it
ASKER
this doesnt work..
$text = 'A Christmas Carol \';
$new_text = rtrim($text, '\');
echo $new_text;
how can I test the other above samples?
$text = 'A Christmas Carol \';
$new_text = rtrim($text, '\');
echo $new_text;
how can I test the other above samples?
This would be a test.
$text = 'A Christmas Carol \';
$new_text = preg_replace('/\\$/','',$text);
$new_text = $new_text[0];
echo $new_text;
ASKER
it shows a blank page while testing
Try this:
$text = 'A Christmas Carol \\';
$new_text = preg_replace('/\\$/','',$text);
$new_text = $new_text[0];
echo $new_text;
Sorry, correction:
$text = 'A Christmas Carol \';
$new_text = preg_replace('/\\$/','',$text);
echo $new_text;
ASKER
both blank page still
Oops, this time then!
$text = 'A Christmas Carol \\';
$new_text = preg_replace('/\\$/','',$text);
echo $new_text;
ASKER
ok the output of that shows as
A Christmas Carol \
and it should be
A Christmas Carol
A Christmas Carol \
and it should be
A Christmas Carol
Ok, solved it - needs 4 backslashes!
$text = 'A Christmas Carol \\';
print "Before:<pre>$text</pre>";
$text = preg_replace("/\\\\$/",'',$text);
print "After:<pre>$text</pre>";
Note this works too:
$text = rtrim($text,'\\');
rtrim will work if you also include the CR & LF
$text = "A Christmas Carol \\";
var_dump($text);
$new_text = rtrim($text, " \\\r\n");
var_dump($new_text);
ASKER
alright so for testing it just needs 4 backslashes but for the normal app it just needs 2 backslashes since its coming from mysql database.. correct?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
got it...thanks a lot TerryAtOpus..
Open in new window