简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM