簡體   English   中英

字符串內的索引替換

[英]Indexed substitution within string

我正在尋找一個帶有特殊HTML標記的字符串,並據此進行解析。 在下面,我將顯示原始字符串后面跟着我想要的解析字符串。 如果有人可以指導我采用正確的編碼方法來實現這一目標,那將是非常棒的。

原始字串:

$string = '<string 1="Jacob" 2="ice cream">{1} likes to have a lot of {2}.</string>';

解析的字符串:

$parsed_string = 'Jacob likes to have a lot of ice cream.';]

編輯:

我忘記添加$ string變量可能具有多個帶有多個選項的字符串,例如$ string變量可能是以下內容:

$string = '<string 1="hot dog">I like to have {1}</string> on <string 1="beach" 2="sun">the {1} with the blazing hot {2} staring down at me.';

我需要一個可以解析上面代碼示例的解決方案。

編輯2:

這是我開發的示例代碼,它不完整並且有一些錯誤。 如果有多個選項,例如1 ='blah'2 ='blahblah',則不會解析第二個選項。

$string = '<phrase 1="Jacob" 2="cool">{1} is {2}</phrase> when <phrase 1="John" 2="Chris">{1} and {2} are around.</phrase>';

preg_match_all('/<phrase ([0-9])="(.*?)">(.*?)<\/phrase>/', $string, $matches);

    print $matches[1][0] . '<br />';
    print $matches[2][0] . '<br />';
    print $matches[3][0] . '<br />';

    print '<hr />';

    $string = $matches[3][0];

    print str_replace('{' . $matches[1][0] . '}', $matches[2][0], $output);

    print '<hr />';

    print '<pre>';
    print_r($matches);
    print '</pre>';
<?php
    $rows = array();
    $xml = "
        <string 1="Jacob" 2="ice cream">{1} likes to have a lot of {2}.</string>        
        <string 1="John" 2="cream">{1} likes to have a lot of {2}.</string>     
    "
    $parser = xml_parser_create();
    xml_parse_into_struct($parser, trim($xml), $xml_values);        
    foreach ($xml_values as $row){
        $finalRow = $row['values'];
        foreach ($row['attributes'] as $att => $attval){
            $finalRow = str_replace ($finalRow, "{".$att."}", $attval);
        }
        $rows[] = $finalRow;
    }
?>

這是一個不使用正則表達式的版本,這似乎更簡單。 我不知道xml解析器如何處理以數字開頭的屬性。

由於$string不是有效的XML(例如,包含數字作為屬性名稱),因此您可以嘗試:

$string = '<string 1="Jacob" 2="ice cream">{1} likes to have a lot of {2}.</string>';
$parsed_string = strip_tags($string);
for ($i = 1; $i <= 2; $i++) {
    if (preg_match('/' . $i . '="([^"]+)"/', $string, $match))
        $parsed_string = str_replace('{' . $i .'}', $match[1], $parsed_string);
}
echo $parsed_string;

更新

您的EDIT現在從在變量中具有一個<string>標記切換為具有多個<string>標記。 這應該適用於多個:

$string2 = '<string 1="hot dog">I like to have {1}</string> on <string 1="beach" 2="sun">the {1} with the blazing hot {2} staring down at me.</string>';
$parsed_string2 = '';
$a = explode('</string>', $string2);
foreach ($a as $s) {
    $parsed_elm = strip_tags($s);
    for ($i = 1; $i <= 2; $i++) {
        if (preg_match('/' . $i . '="([^"]+)"/', $s, $match))
            $parsed_elm = str_replace('{' . $i .'}', $match[1], $parsed_elm);
    }
    $parsed_string2 .= $parsed_elm;
}
echo $parsed_string2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM