首頁  >  文章  >  後端開發  >  PHP去除字串中的所有空格及在每個字元前後加上‘%’

PHP去除字串中的所有空格及在每個字元前後加上‘%’

巴扎黑
巴扎黑原創
2016-11-23 14:03:561031瀏覽

function str_split_unicode($str, $l = 0) {
     if ($l > 0) {
         $ret = array();
         $len = mb_strlen($str, "UTF-8");
         for ($i = 0; $i < $len; $i += $l) {
             $ret[] = mb_substr($str, $i, $l, "UTF-8");
         }
         return $ret;
     }
     return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
 }
 
$str = &#39;  z   十   三&#39;;
echo strlen($str),&#39;--strlen&#39;,&#39;<br>&#39;;
echo mb_strlen($str, &#39;utf-8&#39;),&#39;--mb_strlen&#39;,&#39;<br>&#39;;
$arrstr = str_split($str);
$arrstr = str_split_unicode($str);//符合要求
$temp=&#39;&#39;;
foreach ($arrstr as $val){
$temp.= trim($val);
}
echo $temp, &#39;<br>&#39;;//符合要求,去除空格后的字符串
$arrstr = str_split_unicode($temp);//符合要求
$temp=&#39;%&#39;;
foreach ($arrstr as $val){
$temp.=$val.&#39;%&#39;;
}
echo $temp,&#39;<br>&#39;;//符合要求,加上‘%’后的字符串
echo mb_strlen($temp),&#39;<br>&#39;;
echo mb_strlen($temp, &#39;utf-8&#39;);//符合要求


下面用java程式碼來實作 

/**
 * 
 */
package cn.com.songjy.demo;
/**
 * @author songjianyong
 *
 */
public class LikeSqlConditionDemo {
public static void main(String[] args) {
System.out.println(getLikeSqlCondition("   aa  a d   "));//输出结果是:%a%a%a%d%
}
public static String getLikeSqlCondition(String condition){
if(condition==null || condition.trim().length()==0)
return null;
condition = trim(condition);//去除空格
String[] str = condition.split("");
String temp = "";
for (String string : str) {
temp+=string+"%";
}
return temp;
}
public static String trim(String str){
String temp = "";
for(int i=0; i<str.length(); i++){
temp = (new StringBuilder()).append(temp).append(str.substring(i, i+1).trim()).toString();
}
return temp;
}
}


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn