CdB
CdB

Reputation: 4908

php replace substring with regex

Ok, i know there are trillions of similar questions, but i'm finding it really hard to achieve this. I have some strings of this formats:

$x = '<iframe src="[File:19]"></iframe>';
$y = '<img src=[File:2212] />';
$z = '<source src="[File:42]" />';

I'm trying to get the id given after the File: and also replace the whole [File:xxx] with another string. I'm trying like the following, but it seems i can't fully understand the usage of preg_replace.

$file = ('<iframe src="[File:134]"></frame>');
$rex = "/^.*(\[File:[0-9]{1,}\])/i" ;
if ( preg_match($rex, $file, $match) ) {
    echo 'OK';
}
$file = preg_replace ($rex, "http://lala.com/la.pdf", $file);
echo "<br>".htmlentities($file)."<br>";

Could you please give me some hints on how i can do this?

Thanks in advance.

Upvotes: 1

Views: 2254

Answers (3)

Berry Langerak
Berry Langerak

Reputation: 18859

This should work:

<?php
$formats[] = '<iframe src="[File:19]"></iframe>';
$formats[] = '<img src=[File:2212] />';
$formats[] = '<source src="[File:42]" />';


foreach( $formats as $format ) {

    $regex = '~\[File:(\d+)\]~';

    $replace = function( $matches ) {
        return 'http://lala.com/la.pdf?id=' . $matches[1];
    };

    var_dump( preg_replace_callback( $regex, $replace, $format ) );
}

I've created a lambda for the replacement, because I have a feeling you want to use the id after File: instead of just discarding that. Have fun with it. If you have any questions, do tell.

Upvotes: 1

Toto
Toto

Reputation: 91385

Change these 2 lines

$rex = "/^.*(\[File:[0-9]{1,}\])/i" ;

$file = preg_replace ($rex, "http://lala.com/la.pdf", $file);

to:

$rex = "/^(.*)\[File:[0-9]{1,}\]/i" ;

$file = preg_replace ($rex, "$1http://lala.com/la.pdf", $file);

This will capture what is before [File...] into group 1, then in the replace part, add this group (i.e. $1) in front of the replace string.

It can be rewritten as:

$rex = "/\[File:\d+\]/i" ;

$file = preg_replace ($rex, "http://lala.com/la.pdf", $file);

Upvotes: 1

Mr. Llama
Mr. Llama

Reputation: 20899

This should do the trick:

preg_match('/\[File:(\d+)\]/i', $str, $match)

$match[0] will have the whole string, $match[1] will have just the number.
After the regex match, you can use str_replace to remove $match[0] from the string.

Example:

$x = '<iframe src="[File:19]"></iframe>';
preg_match('/\[File:(\d+)\]/i', $x, $match);
var_dump($match);

Gives:

array(2) {
  [0]=>
  string(9) "[File:19]"
  [1]=>
  string(2) "19"
}

Upvotes: 1

Related Questions