1

中文字与普通文字相结合时如何<br>在汉字前加。

<?php

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

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

?>

输出:

Hello World</br>自立合作社
4

2 回答 2

1

这肯定不是最好的解决方案,但一种方法是匹配一串 ASCII 字符,[\x00-\x7F]+后跟一个非 ASCII 序列(用 否定的相同模式^)。它没有专门针对中文,但由于中文 Unicode 字符的范围不同,这很棘手。

$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);
于 2013-07-14T13:35:29.857 回答
1

我不是中国人,但我希望这会有所帮助。

当您使用 php 时,您可以将 preg_replace 与前瞻构造一起使用。它将用 <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{Han} 会匹配所有中文字符,因此请在此处查看有关 unicode 字符的更多信息

可能这个也有帮助

希望这可以帮助。祝你好运!;)

于 2013-07-14T14:14:07.593 回答