user1179177
user1179177

Reputation: 23

how to return matches value using preg_replace()

please how do that ?

<?php
$string = '<inc="file.php">';
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#',include("$1"),$string);
?>

the output is return $1

i need to return include file.php

Upvotes: 0

Views: 1605

Answers (3)

Zombaya
Zombaya

Reputation: 2258

I think it should be

return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#','include("'.$1.'")',$string);

The second parameter should be a string.

Upvotes: 1

meticulousMisnomer
meticulousMisnomer

Reputation: 81

I'm not exactly sure what you're trying to do, but try using preg_match over preg_replace.

It gathers the matches into an array if you use it like shown:

preg_match('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', $string, $matches);

And then the matches are stored in the $matches array. You can then loop over them using foreach.

Upvotes: 1

Ry-
Ry-

Reputation: 224952

If you have PHP 5.3 or higher:

<?php
$string = '<inc="file.php">';
return preg_replace_callback('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', function($matches) {
    return include $matches[1];
}, $string);
?>

Upvotes: 4

Related Questions