Search code examples
phpregexphpstorm

PhpStorm regular expression search and replace it


I use PhpStorm, this is I want to search and modify content.

<img src="/images/test1.png" class="bar" />
<img src="/images/test2.jpg" id="test" />
<div id="content">
    <img src="/assets/images/test3.png" />
</div>

I want add a helper into the src path. After modify

<img src="<?php helper_src('/images/test1.png'); ?>" class="bar" />
<img src="<?php helper_src('/images/test2.jpg'); ?>" id="test" />
<div id="content">
    <img src="<?php helper_src('/assets/images/test3.png'); ?>" />
</div>

I used the regular expression to find it <img src=(\'|\")\/.*\.(jpg|png), how can I use Replace in Path to replace all my search result? Thanks.


Solution

  • If you use the following (slightly modified) regular expression:

    <img src=(?:\'|\")(?<path>\/.*\.(?:jpg|png))(?:\'|\")
    

    you can use the below "replace" value:

    <img src="<?php helper_src('$1'); ?>
    

    It contains a template that you described, and $1 puts the first matched group (it is called path) into it.