PHP中的字符串替换
我正在开发一个测验系统..
假设我有这个字符串..
$my_string = "The language i use is [ans]php[/ans]";
输出是:
我使用的语言是 [input name='ans' id='ans' /] //Textbox by 我使用 preg_replace 函数的方式
但没有运气..
我的代码:
$string = 'The quick [j]brown[/j] fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '!\[j\]]';
$patterns[1] = '/brown/';
$patterns[2] = '\[/j\]!';
$replacements = array();
$replacements[0] = '';
$replacements[1] = '<input type="text" name="j_1" id="j_1" />';
$replacements[2] = '';
echo preg_replace($patterns, $replacements, $string);
输出是:
The quick []<input type="text" name="j_1" id="j_1" /> [/] fox jumped over the lazy dog.
期望:
The quick <input type="text" name="j_1" id="j_1" /> fox jumped over the lazy dog.
如果你们能提供帮助,我真的很感激..
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该按照您的描述工作。
$string = '敏捷的[j]brown[/j]狐狸跳过了懒狗。';
$string = preg_replace('/\[j\](.*)\[\/j\]/', '
print $string;
对于上面的示例,您还可以通过在替换字符串中使用
$1
来访问标记之间替换的内容。如果你想运行另一个 preg_replace 来获取答案,你可以这样做:
$string = 'The Quick [j]brown[/j] Fox Jumped over the Lazy Dog.';
$answer = preg_replace('/(.*)\[j\](.*)\[\/j\](.*)/', '$2', $answer);
< br>print $answer;
使用
$2
的原因是它是字符串的第二个匹配项。 (注意有三个(.*)
,每个都匹配某些内容。因此,$1
等于The Quick
、$2
等于brown
,$3
等于狐狸跳过了懒狗。
。)This should work as your described.
$string = 'The quick [j]brown[/j] fox jumped over the lazy dog.';
$string = preg_replace('/\[j\](.*)\[\/j\]/', '<input type="text" name="j_1" id="j_1" />', $string);
print $string;
You can also access whatever is replaced between the tags by using
$1
in your replace string for the example above.If you wanted to run another preg_replace to grab what the answer should be, you would do something like this:
$string = 'The quick [j]brown[/j] fox jumped over the lazy dog.';
$answer = preg_replace('/(.*)\[j\](.*)\[\/j\](.*)/', '$2', $answer);
print $answer;
The reason you use a
$2
is because it's the second match of the string. (Notice how there are three(.*)
, each of those matches something. So,$1
would equalThe quick
,$2
would equalbrown
, and$3
would equalfox jumped over the lazy dog.
.)试试这个:
查看
Try this:
See it