dro62273 2014-01-28 19:37
浏览 86
已采纳

在html文档中将英文数字转换为阿拉伯数字

I want to convert English digits (0,1,2,3,...) to Arabic digits (۰,۱,۲,۳,...) in content of some HTML document using a PHP function.
I wrote this function:

function en2ar($str) {
    $ends = array('0','1','2','3','4','5','6','7','8','9');
    $ards = array('۰','۱','۲','۳','۴','۵','۶','۷','۸','۹');
    return str_replace($ends,$ards,$str);
}

but it converts all digits in document, while I want to convert only digits in content of document.
for example, I want to convert:

<h1 style="color: #333;">1</h1>
<div style="width: 180px;">2</div>

to:

<h1 style="color: #333;">۱</h1>
<div style="width: 180px;">۲</div>

but it converts to:

<h۱ style="color: #۳۳۳;">۱</h۱>
<div style="width: ۱۸۰px;">۲</div>

and makes the document invalid.

  • 写回答

3条回答 默认 最新

  • dtwr2012 2014-01-28 20:14
    关注

    You can try using an HTML parser like DOMDocument.

    Here's an example:

    $html = 
    '<!DOCTYPE HTML>
    <html>
    <head></head>
    <body>
        <h1 style="color: #333;">1</h1>
        <div style="width: 180px;">2</div>
    </body>
    </html>';
    
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $doc->encoding = 'UTF-8'; //Appropriate encoding HERE
    $root = $doc->documentElement;
    
    var_dump($doc->saveHTML());
    iterate($root);
    var_dump($doc->saveHTML());
    
    function iterate($node)
    {
        if($node->nodeType === XML_TEXT_NODE) {
            $node->nodeValue = en2ar($node->nodeValue);
        }
        if ($node->hasChildNodes()) {
            $children = $node->childNodes;
            foreach($children as $child) {
                iterate($child); 
            }
        }
    }
    

    To save the output to a variable use:

    $var = $doc->saveHTML();

    Output:

    string '<!DOCTYPE HTML>
    <html><head></head><body>
        <h1 style="color: #333;">1</h1>
        <div style="width: 180px;">2</div>
    </body></html>
    ' (length=135)
    string '<!DOCTYPE HTML>
    <html><head></head><body>
        <h1 style="color: #333;">۱</h1>
        <div style="width: 180px;">۲</div>
    </body></html>
    ' (length=147)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?