简体   繁体   English

PHP在一个字符串中找到多个花括号并替换其中的文本

[英]PHP find multiple curly braces in a string and replace the text inside

I have string in my database like 我的数据库中有字符串

Label is {input:inputvalue} and date is {date:2013-2-2}

How can I extract input and inputvalue from the first brace, and date and 2013-2-3 from the second brace and so on? 如何从第一个大括号中提取输入和输入值,以及从第二个大括号中提取日期和2013-2-3,依此类推? So that displays like 所以显示像

Label is <input name="input" value="input_value"> and date is <input name="date" value="2013-2-2"> 

Below function works only if the string has {input} or {date} 仅当字符串具有{input}或{date}时,以下函数才有效

function Replace_brackets($rec){
    $arr = array(" <input name="input" value='input'> ",
                 " <input name="date" value='date'> ");
    $arr1 = array('{input}','{date}');
    $itemvalue=str_replace($arr1,$arr,$rec);
    return $itemvalue;
}

There might be more or less braces on the text such as 2 input braces and 4 date braces. 文本上可能有大括号,例如2个输入大括号和4个日期大括号。

Any ideas? 有任何想法吗?

preg_replace() with back references will work in this case http://php.net/manual/en/function.preg-replace.php : 在这种情况下,带有反向引用的preg_replace()可以在以下情况下使用: http : //php.net/manual/zh/function.preg-replace.php

<?php
$s = "Label is {input:inputvalue} and date is {date:2013-2-2}";
print preg_replace( "/{([^:}]*):?([^}]*)}/", "<input name='\\1' value='\\2'>", $s );
?>

Or if you need to parse the name and value pairs, as @Jack pointed out, you could use the preg_replace_callback() version (you don't actually need to use htmlspecialchars() on the attribute values though. Replace htmlspecialchars() with whatever parsing function is applicable): 或者,如果您需要解析名称和值对(如@Jack所指出的那样),则可以使用preg_replace_callback()版本(尽管实际上不需要在属性值上使用htmlspecialchars()。用任何内容替换htmlspecialchars())解析功能适用):

print preg_replace_callback( "/{([^:}]*):?([^}]*)}/", "generate_html", $s );

function generate_html( Array $match )
{
return "<input name='".htmlspecialchars($match[1])."'    value='".htmlspecialchars($match[2])."'>";
}

You could use a regex and the preg_replace_callback function 您可以使用正则表达式和preg_replace_callback函数

preg_replace_callback('~(\\{[^}]+\\})~', $callback, $subject);

where subject is your text and callback a function which handels the given input string and returns your replacement 这里的主题是您的文本,并回调一个处理给定输入字符串并返回替换项的函数

for simple expressions you could use the next example, but this could be transformed into an single preg_replace(without the callback) 对于简单表达式,您可以使用下一个示例,但是可以将其转换为单个preg_replace(不带回调)

$callback = function($string) {
    preg_match('~\\{([^:]):(.*)\\}~', $string, $m);
    return "<input name=\"{$m[1]}\" value=\"{$m[2]}\">";
};

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

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