This is probably very simple, but I couldn't find it.
I need to search a string for a group of chinese characters, and replace them with an english word.
So basically search a string for the first character that is not a-z, 1-9 or - , but I couldn't find how.
I'm currently using string pointers at the start and end of the characters to achieve the result, which working is fine, but looking pretty sloppy.
$str_start = strpos ( $switcher , 'start' );// get the string start
$str_start +=5;//Add 5 to it to make up for the length of search term
$str_end = strpos ( $switcher , '/' , $str_start );//find the end
$length = $str_end - $str_start;//get the length of chinese characters
echo substr_replace ( $switcher , 'product-category' , $str_start , $length );//replace with english word
EDIT: Actual example added for clarity:
<option value="http://imw1248.info/商品分类/bamboo-cutting-board/small-cutting-boards/">English</option>
Should be:
<option value="http://imw1248.info/product-category/bamboo-cutting-board/small-cutting-boards/">English</option>
Code:
$str_start = strpos ( $switcher , '.info/' );
$str_start +=6;
$str_end = strpos ( $switcher , '/' , $str_start );
$length = $str_end - $str_start;//get the length of chinese characters
echo substr_replace ( $switcher , 'product-category' , $str_start , $length );
To search and replace Chinese characters I usually use this regexp
$charFound = preg_match( '/^[\x{4e00}-\x{9fa5}]+$/u', trim( $data["value"] ), $arrayOfCharacters );
This will find all Chinese characters only in the given string and return them. That is one solution to get them in a strict and validated format and also make sure your code works. You could easily extend and do more with that.
I would use http://www.php.net/manual/en/book.mbstring.php handling to find and replace specific sets of characters if a match is found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With