Link to home
Start Free TrialLog in
Avatar of XK8ER
XK8ERFlag for United States of America

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
Avatar of theodorejsalvo
theodorejsalvo
Flag of United States of America image

Use this.
$str = preg_replace('/\\$/','',$str);

Open in new window

Avatar of Terry Woods
$string = preg_replace("@\\$@","",$string);
Avatar of delizeka
delizeka

I think you can use rtrim function to remove last backslash character at the end of string.

Example :


$text = 'A Christmas Carol \';
$new_text = rtrim($text, '\');

//new_text now does not contain a back slash at the end of it

Open in new window

Avatar of XK8ER

ASKER

this doesnt work..

$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;

Open in new window

Avatar of XK8ER

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;

Open in new window

Sorry, correction:


$text = 'A Christmas Carol \';
$new_text = preg_replace('/\\$/','',$text);
echo $new_text;

Open in new window

Avatar of XK8ER

ASKER

both blank page still
Oops, this time then!
$text = 'A Christmas Carol \\';
$new_text = preg_replace('/\\$/','',$text);
echo $new_text;

Open in new window

Avatar of XK8ER

ASKER

ok the output of that shows as

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>";

Open in new window

Note this works too:
$text = rtrim($text,'\\');

Open in new window

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);

Open in new window

Avatar of XK8ER

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
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of XK8ER

ASKER

got it...thanks a lot TerryAtOpus..