1

Hi I have to remove a part of a string. The code is as follow:-

$string = "19Apr2016";
$search = '_'.$string;

$v1 = "DA6220_19Apr2016";
$v1 = preg_replace("([$search])", "", $v1);
echo $v1 ;

The following code only returns D as output. I want remove _19Apr2016 from the string. Please point out what i am doing wrong.

4
  • What part of the string DA6220_19Apr2016 you want to remove ? Commented May 20, 2016 at 13:56
  • 1
    try this: preg_replace("/$search/", "", $v1); Commented May 20, 2016 at 13:57
  • don't wrap your regex with square brackets Commented May 20, 2016 at 13:57
  • 1
    @FrayneKonok Thank you it worked Commented May 20, 2016 at 13:59

2 Answers 2

1

Replace,

preg_replace("([$search])", "", $v1);

with,

preg_replace("/$search/", "", $v1);
Sign up to request clarification or add additional context in comments.

Comments

0

[$search] is a character class that means one of character in the list _,1,9,A,p,r,2,0,1,6, when you replace in the string $v1 = "DA6220_19Apr2016" every character that is in the list, you get D, the only character that is not in the list.

You want to use:

$v1 = preg_replace("($search)", "", $v1);

or, using more common regex delimiter:

$v1 = preg_replace("/$search/", "", $v1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.