doumi9618 2013-02-14 06:46
浏览 59
已采纳

php - 正则表达式用大括号和引号替换字符串

I see a lot of questions here regarding regex in general , but the problem is that they are usually (like mine) quite localized, and difficult to deduct if one is not a regex expert ..

My string involves characters like quotes and braces , which are quite known for making regex more difficult.

I would like to know the expression strings (search, replace) I need in order to perform this task.

in other words , in :

 ereg_replace (string pattern, string replacement, string subject) 

I will need the string pattern and string replacement expressions.

my string is

array('val' => 'something', 'label' => 'someword'),

I need to change the last part :

'label' => 'someword'),

to

'label' => __('someword','anotherstring')),

I will be using php for that , but I would also like to test it ( and also use in other cases) with Notepad ++ . ( I do not know if it actually changes something regarding the search and replace strings ).

Note that the string someword can also be SomeWord or SOMEWORD or even Some word or Some_Word on cases, meaning it can contain spaces, underscores or actually almost any character from within...)

Edit I : forgot to mantion that the __() part is of course wordpress textdomain function for translations . e.g. __('string','texdomain')

Edit II :

I am sorry if I come off too exigent or demanding in the comments , I really do try to UNDERSTAND and not only copy-paste a solution that might not work for me in other cases .. :-)

Edit III :

By the help of THIS tool , I understood that my basic misunderstanding is the possibility to use VARIABLES inside regex . The $1 is actually all I needed for better understanding .

the (incredibly simple) pattern that will work also in notepad++

Pattern: 'label' => ('.*')

Replace: 'label' => __(\1,'textdomain')

(In notepad++ it is called Tag Region (not var) and it is marked as \1

  • 写回答

3条回答 默认 最新

  • duannan3959 2013-02-14 07:13
    关注

    If you will always be looking for the label key, you should be able to do something like this:

    $pattern = "/array\((.*), 'label' => '(.*)'/U";
    $added_string = 'anotherstring';
    $replacement = 'array($1, ' . "'label' => __('" . '$2' . "','$added_string'";
    $final_string = preg_replace($pattern, $replacement, $original_string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题