Ayxan Emiraslanli
Ayxan Emiraslanli

Reputation: 87

php preg_match_all and preg_replace

i want to encode all input values to base64 encoded. So i need some help... My code is:

$check_hash = preg_match_all('/<input type="text" value="(.*?)">/mis', $ays, $hashtweet);

$ays = preg_replace('/<input type="text" value="(.*?)">/', base64_encode($hashtweet[1]), $ays);

echo $ays;

And my page is here: http://www.ceay.biz/test/vkmp3/

But it dont gives me what i want. Can anyone help me?

Upvotes: 1

Views: 578

Answers (3)

Orangepill
Orangepill

Reputation: 24645

Use preg_replace_callback to do this (requires php 5.3 for closure)

$ays = preg_replace_callback('/value="(.*)"/', function ($match) {
                          return "value=\"".base64_encode($match[1])."\""; }, $ays);

for pre php 5.3 environments

if (!function_exists("valueReplacer")){
    function valueReplacer ($m){
        return "value=\"".base64_encode($m[1])."\""; 
    }
}
$ays = preg_replace_callback('/value="(.*)"/', "valueReplacer", $ays);

Upvotes: 2

Yago Riveiro
Yago Riveiro

Reputation: 727

You can check this:

$string = '<input type="text" value="http://cs9-10v4.vk.me/p1/63ec3a36b2eb1c.mp3">';
preg_match('/<input type="text" value="(.*)">/', $string, $matches);
$string = preg_replace('/(<input type="text" value=").*(">)/', "$1".base64_encode($matches[1])."$2", $string);
var_dump($string);

Upvotes: 0

anubhava
anubhava

Reputation: 785306

You will need to call preg_replace_callback in order to execute PHP code as replacement:

$ays = preg_replace_callback('/<input type="text" value="(.*?)">/', function ($m) {
                             return base64_encode($hashtweet[1]); }, $ays);

Upvotes: 1

Related Questions