0

I want to write a regex for the below PHP block and want to replace it with the actual image path.

<?php echo $imagePath; ?>

I have tried

str.replace(/<\?[=|php]?[\s\S]*?\?>/g, 'images/dir1/');

but it is replacing all other PHP blocks of the page also. I want a regex which replaces a particular PHP block.

3
  • 1
    you should not operate php code from js code. This <?php echo $imagePath; ?> should be rendered, then you may do replacement Commented Mar 19, 2017 at 18:42
  • Why not use PHP? Commented Mar 19, 2017 at 18:46
  • 1
    I know we should not. But I am using ckEditor to edit php files and there i want actual path to show images. ckEditor can't render php tags. Commented Mar 19, 2017 at 18:47

1 Answer 1

1

Try using the following regex ...

<\?php\secho\s\$imagePath;\s\?>

see regex demo

JavaScript

var phpblock = '<?php echo $imagePath; ?>';
var result = phpblock.replace(/<\?php\secho\s\$imagePath;\s\?>/g, 'images/dir1/');
console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

Hey Thanks. It worked. Earlier i tried <\?php\secho \$imagePath;\s\?>. and missed \s between echo and imagePath. Silly.. :P
@AbhiAndhariya You're Welcome :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.