2013-07-14 54 views
1

如果中文字符與正常文字結合使用,如何在漢字前添加<br>在漢字前添加'<br>'

<?php 

$string = 'Hello World 自立合作社'; 

/* 
this is what I tried: 
preg_match('/\\p{Han}/u', $string, $matches); 
print_r($matches) 
*/ 

?> 

輸出:

Hello World</br>自立合作社 
+0

它總是單行,還是'$ string'可以多行? –

+0

也許你可以使用正則表達式? – Rainulf

+0

[你有沒有試過?](http://whathaveyoutried.com/) –

回答

1

這當然不是最好的解決方案,但是一種方法將是通過[\x00-\x7F]+後跟一個非ASCII序列以匹配的ASCII字符的字符串(相同圖案否定與^)。它並沒有專門針對中國人,但由於the varied ranges of Chinese Unicode characters,這是棘手的。

$string = 'Hello World 自立合作社'; 
// Capture ASCII sequence into $1 and non-ASCII into $2 
echo preg_replace('/([\x00-\x7F]+)([^\x00-\x7F]+)/', '$1<br/>$2', $string); 

// Prints: 
// Hello World 
// 自立合作社 

http://codepad.viper-7.com/1kqpOx

其實,這裏的,它通過\p{Han}專門針對中國字符的改進版本。對於空格,$2捕獲還包括\s

// This matches any non-Chinese in $1 followed by Chinese (and whitespace) in $2 
echo preg_replace('/([^\p{Han}]+)([\p{Han}\s]+)/', '$1<br/>$2', $string); 
1

我不是中國人,但我希望這可以幫助。

由於您正在使用php,因此您可以使用preg_replace與look ahead construct。 它將用<br>替換所有空白字符(中文字符前的那些字符)。

$string = 'Hello World 自立合作社'; 
$pattern = "/\\p{Z}(?=\\p{Han})/ui"; // matches a white space before Chinese character. 

$brStr = preg_replace($pattern, "<br>", $string); 
echo $brStr; 

我不知道會\ p {}漢匹配所有中國字符,以便籤上Unicode字符here

May be this one will help too

希望這有助於更多的信息。祝你好運! ;)