简体   繁体   中英

Regex to replace a special character in PHP?

I have problem with a special character § . I want to replace multiple occurrences of § with single § . The following regex works fine on Regex 101 .

$file_data = file_get_contents($file_name);
$file_data = preg_replace('/\§+/g', '§',$file_data);

It changed

§§§§§§§§§This free 3D robot game could redefine how kids learn to codeDigital Trends It's hard to get kids to code. Up until very recently, it was largely ....

to

§This free 3D robot game could redefine how kids learn to codeDigital Trends It's hard to get kids to code. Up until very recently, it was largely ....

However, it is not working on the server after I upload it. Here is the var_dump($file_data) by PHP

§§§§§§§§ This free 3D robot game could redefine how kids learn to codeDigital Trends It's hard to get kids to code. Up until very recently, it was largely ....

So, there seems to be an additional character  before every § in the var_dump . The extra character  does not show up on webpage when echoed as HTML. It just shows up during plain PHP var_dump . How can I replace multiple occurrences of § using regex in PHP?

You will need to set the u (utf-8) modifier:

From perlre documentation:

/u means to use Unicode rules when pattern matching. On ASCII platforms, this means that the code points between 128 and 255 take on their Latin-1 (ISO-8859-1) meanings (which are the same as Unicode's)....

$output = preg_replace('/§+/u', '§', $input);
                         // ^ 
$str="§§§§§§§§§This free 3D robot game could redefine how kids learn to codeDigital Trends It's hard to get kids to code. Up until very recently, it was largely ....";
$pttn='@\§{2,}@um';
echo preg_replace( $pttn,'§',$str );

/* will output */
/*
   §This free 3D robot game could redefine how kids learn to codeDigital Trends It's hard to get kids to code. Up until very recently, it was largely .... 
*/

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