SNG
SNG

Reputation: 357

Removing string between special characters in php

I want to remove the string which is placed in between "^".

my code:

$search = "/[^](.*)[^]/";
$replace = "";
$string = "^5561^18.5018,73.8636|^5662^20.1738,72.7640";
echo preg_replace($search,$replace,$string);

but my output: ^^..^^..

desired output: "8.5018,73.8636|20.1738,72.7640";

pls let me know how to achieve this. Thanks in advance.

Upvotes: 0

Views: 36

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627535

The [^] pattern is an invalid character class. In JavaScript, it would match any char since it is parsed as a non-nothing, but in PHP, it is an empty (and thus invalid) negated character class.

You need to match ^ with \^ and either use a lazy dot pattern or a [^^]* to match any chars but ^ in between:

$search = '/\^[^^]*\^/';
$replace = "";
$string = "^5561^18.5018,73.8636|^5662^20.1738,72.7640";
echo preg_replace($search,$replace,$string);
// => 18.5018,73.8636|20.1738,72.7640

See the PHP demo.

Details

  • \^ - a ^ char
  • [^^]* - any 0+ chars other than ^ (the first ^ denoted a negated character class and the second one is a literal ^)
  • \^ - a ^ char.

Upvotes: 1

Related Questions