在php中搜索字符串中没有的字符

时间:2014-04-30 04:34:17

标签: php

这可能很简单,但我无法找到它。

我需要在字符串中搜索一组中文字符,并用英文单词替换它们。

所以基本上搜索一个不是a-z,1-9或 - 的第一个字符的字符串,但我无法找到。

我目前在字符的开头和结尾使用字符串指针来实现结果,工作正常,但看起来很草率。

   $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

编辑:为清晰起见添加了实际示例:

<option value="http://imw1248.info/商品分类/bamboo-cutting-board/small-cutting-boards/">English</option>

应该是:

<option value="http://imw1248.info/product-category/bamboo-cutting-board/small-cutting-boards/">English</option>

代码:

       $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 );

1 个答案:

答案 0 :(得分:5)

要搜索和替换中文字符,我通常使用此正则表达式

$charFound = preg_match( '/^[\x{4e00}-\x{9fa5}]+$/u', trim( $data["value"] ), $arrayOfCharacters );

这将只找到给定字符串中的所有中文字符并返回它们。这是一种解决方案,可以使用严格且经过验证的格式,并确保您的代码正常工作。你可以轻松扩展并做更多的事情。

如果找到匹配项,我会使用http://www.php.net/manual/en/book.mbstring.php处理来查找和替换特定的字符集。