Home > OS >  Find and replace special x character from string in php
Find and replace special x character from string in php

Time:02-20

I am working with the stripe webhook system and they include a special x character in their subscription description field. Below is an example.

"description": "1 × Base Package (at $25.00 / year)",

When this description is entered into a utf8 formatted email the character is lost and replaced with an A character. I have tried a grocery list of functions attempting to find this character. I wish to simply replace it with either a standard x or html character.

CodePudding user response:

You can just use str_replace. This function is binary-safe.

$string = "1 × Base Package (at $25.00 / year)";

$strClean = str_replace('×','x',$string);

The first 'x' is the orginal Unicode-Char, second 'x' is ASCII. This becomes visible with a special debugger.

$string: string(36) UTF-8   1\x20\u{d7}\x20Base\x20Package\x20(at\x20$25.00\x20/\x20year)

$strClean: string(35) ASCII 1\x20x\x20Base\x20Package\x20(at\x20$25.00\x20/\x20year)

To make the difference more visible in the code, you can also use

$strClean = str_replace("\u{d7}",'x',$string);
//or
$strClean = str_replace("\xc3\x97",'x',$string);

These are ultimately just different spellings for the same Unicode Character “×” (U 00D7)

  •  Tags:  
  • php
  • Related