简体   繁体   English

PHP替换特殊字符内的字符串

[英]PHP replace string inside special characters

I know it's easy for the most of the people, but it isn't for me, regular expressions pain me alot. 我知道对大多数人来说这很容易,但是对我来说却不容易,正则表达式让我很痛苦。

What I need is to replace all the string inside the '%s' ... '%s' for a element: 我需要的是将'%s'...'%s'内的所有字符串替换为一个元素:

original: I have read and accept %sthe terms of booking%s 原文:我已阅读并接受%s预订%s的条款

what i want is to replace all the '%sthe terms of booking%s' for something like: 我想要的是将所有“%s.booking%s的条款”替换为:

<a href="..." id="enlaceCondiciones" target="_blank" >Condiciones de venta</a>

Thanks in advance. 提前致谢。

PD: Text inside the '%s' - '%s' changes depending on the user language, so a simple str_replace is not a solution in this case PD:'%s'-'%s'内的文本根据用户语言而变化,因此在这种情况下,简单的str_replace不是解决方案

$output = preg_replace("/%s(.+)%s/", "<a href="..." id="enlaceCondiciones" target="_blank" >$1</a>", '%sthe terms of booking%s');

$输出:

<a href="..." id="enlaceCondiciones" target="_blank" >the terms of booking</a>

I assume you're hacking together a basic templating system and want to replace all of the %s...%s tags in a string without necessarily knowing which are present. 我假设您正在一起使用一个基本的模板系统,并且想替换字符串中的所有%s...%s标签,而不必知道其中存在哪些。 You'd need to do this in 3 steps. 您需要3个步骤。

  1. Find all the tags: 查找所有标签:

     preg_match_all('/(%s[^%]%s)/', $input, $matches); 
  2. Get your replacements. 获取替代品。 This is dependent on your code, but basically just loops through $matches . 这取决于您的代码,但是基本上只是循环$matches

  3. Replace the tags, you can do this in one batch by loading your searches and replacements into arrays: 替换标签,您可以通过将搜索和替换内容加载到数组中来批量完成此操作:

     str_replace(array('%sone%s','%stwo%s'), array('uno', 'dos'), $input); 

As a note, you should always try to use the basic string functions when possible. 需要注意的是,您应该尽可能尝试使用基本的字符串函数。 Regular expressions incur overhead in processing and memory use that are unnecessary when doing simple operations. 正则表达式会产生处理和内存使用方面的开销,这在执行简单操作时是不必要的。

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

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