Aristona
Aristona

Reputation: 9341

preg_replace_all() related issue

I am currently making a BBCode class for my website. I need to do the following.

function bbCode([skill]Q[/skill]_________[skill]Q[/skill]_________[skill]Q[/skill]);

bbCode function has to replace all Q's between [skill] and [/skill] tags, and replace it with $skillArray['Q'] value. ($skillArray is character dependant.)

How can I do this?

A little clearer version is:

  1. For example you're on a page of "Orc" character.
  2. [skill]Q[/skill] tag should get "Orc's Q skill name" automatically.
  3. For example you're on a page of "Hunter" character.
  4. [skill]Q[/skill] tag should get "Hunter's Q skill name" automatically.

Ps. Don't want to use explode.

Upvotes: 2

Views: 7509

Answers (3)

user557846
user557846

Reputation:

<?php
$skillArray=array('Q'=>'fishing');
$txt="test [skill]Q[/skill]  test";
$txt=preg_replace("#\[skill\](.*)\[\/skill\]#e",'$skillArray["$1"]',$txt);
echo $txt; //test fishing test
?>

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57660

This is what you need

$data = "[skill]Q[/skill]_________[skill]Q[/skill]_________[skill]Q[/skill]";
$r['Q'] = "Yahoo";
function b($a){
    global $r;
    return $r[$a[1]];
}
$data = preg_replace_callback('|\[skill\](Q)\[\/skill\]|', 'b' , $data);
var_dump($data);

If you want to replace all the Qs with single "Yahoo" use Q+ instead of Q. If you want to match all words use \w+.

Upvotes: 1

Ashley Banks
Ashley Banks

Reputation: 528

Assuming the tags you want to be replaced are within some form of template, you could use file_get_contents and then loop through the tags you want to replace with the desired values, for example:

$file = file_get_contents ( 'yourfile.php' );

$skillArray = array ( 'Q' => 'Hunter name' );

foreach ( $skillArray as $key => $val )
{
    $file = str_replace ( '[skill]' . $key . '[\skill]', $val, $file );
}

Thats just a completely rough example, but if I'm understanding what you are trying to do; that should be along the right lines....

Upvotes: 1

Related Questions