将范围或某些标记添加到短语中的其他语言文本

时间:2014-05-25 06:48:23

标签: php unicode character unicode-string

在PHP变量中,存在混合语言上下文。一个例子如下:

$variable="This is sample text I am storing in the variable. இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன"

因此变量$variable包含英语和其他语言(上例中的泰米尔语)。

现在我需要添加一个包含泰米尔文本的类的标记,例如:

$variable="This is sample text I am storing in the variable. <span class='tamil'>இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன</span>"

如何省略英文字母和标点符号并将<span>完全添加到其他语言句子或段落?

2 个答案:

答案 0 :(得分:2)

您可以使用unicode系列创建正则表达式,这有助于您在文本中找到tamil字符:http://unicode.org/charts/PDF/U0B80.pdf

[\u0B80-\u0BFA-]*

我为这个例子组建了一个游乐场,以便你可以改进它以完成你需要做的事情。

http://regex101.com/r/wT8hP4

以下不是镀金代码,但希望它能帮助您入门。

<?php

$variable="This is sample text I am storing in the variable. இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன";

echo add_tamil_class($variable);

/**
 * Adds a HTML Span tag around tamil text using regex
 */
function add_tamil_class($text) {

    preg_match_all("/[\x{0B80}-\x{0BFA}]+/u", $text, $matches);

    $tamilSentence = implode(' ', $matches[0]);
    return str_replace(
        $tamilSentence,
        "<span class='tamil'>".$tamilSentence."</span>",
        $text
        );
}

答案 1 :(得分:1)

正如Filype所说,我们可以使用unicode范围。

即使在像'英语'这样的情况下,这也应该匹配 - &gt; '泰米尔' - &gt; '英语' - &gt; “泰米尔”。虽然它会在空间中包含额外的空间。

/**
 * @param String $str Input UTF-8 encoded string.
 */
function encapsulate_tamil($str)
{
   return preg_replace('/[\x{0B80}-\x{0BFF}][\x{0B80}-\x{0BFF}\s]*/u',
      '<span class=\'tamil\'>$0</span>', $str);
}