Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search string in php for characters that are not

Tags:

php

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 );
like image 749
Talk nerdy to me Avatar asked Apr 30 '14 04:04

Talk nerdy to me


Video Answer


1 Answers

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.

like image 112
Cleric Avatar answered Oct 12 '22 08:10

Cleric