简体   繁体   English

添加“ <br> &#39;汉字之前

[英]Add '<br>' before chinese character

How to add <br> before Chinese character if Chinese wording is combined with normal text. 如果中文措辞与普通文本结合使用,如何在中文字符前添加<br>

<?php

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

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

?>

Output: 输出:

Hello World</br>自立合作社

This is surely not the best solution, but one approach would be to match a string of ASCII characters via [\\x00-\\x7F]+ followed by a non-ASCII sequence (same pattern negated with ^ ). 当然,这不是最佳解决方案,但是一种方法是通过[\\x00-\\x7F]+匹配一个ASCII字符字符串,然后是一个非ASCII序列(相同的模式,用^取反)。 It does not target Chinese specifically, but that is tricky owing to the varied ranges of Chinese Unicode characters . 它没有专门针对中文,但是由于中文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 http://codepad.viper-7.com/1kqpOx

Actually, here's an improved version that does specifically target Chinese characters via \\p{Han} . 实际上,这是一个改进的版本,专门通过\\p{Han}定位汉字。 The $2 capture also includes \\s for whitespace. $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);

I am no Chinese but I hope this helps. 我不是中国人,但我希望这会有所帮助。

As you are using php you can use preg_replace with look ahead construct . 当您使用php时,可以将preg_replace与前瞻构造一起使用 It will replace all white space characters (those before chinese character) with a <br>. 它将用<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;

I don't know will \\p{Han} match all Chinese characters so checkout more info on unicode characters here 我不知道\\ p {Han}是否会匹配所有汉字,因此请在此处查看有关Unicode字符的更多信息

May be this one will help too 也许这也会有所帮助

Hope this helps. 希望这可以帮助。 Good luck! 祝好运! ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM