ajl80
ajl80

Reputation: 43

Creating my own tags with preg replace

I'm trying to use add my own tags onto site content so the user can add a specified tag and it replaces with the relevant content. for example [company_address]

I'm using preg_replace($patterns, $replacements, $content);

but it fills the page with scrambled text.

function search4Tags($content){

    $patterns = array();
    $patterns[0] = '/[company_name]/';
    $patterns[1] = '/[company_logo]/';
    $patterns[2] = '/[company_address]/';

    $replacements = array();
    $replacements[0] = $_SESSION['company_name'];
    $replacements[1] = $_SESSION['company_logo'];
    $replacements[2] = $_SESSION['company_address'];

    return preg_replace($patterns, $replacements, $content);
}

Upvotes: 0

Views: 49

Answers (2)

imnotanelephant
imnotanelephant

Reputation: 862

As mentioned in a comment above, you don't need preg_replace for this. str_replace() will do everything you need and more. And in exactly 1 line less, too.

E.G.

    $this->body = str_replace('[company_name]', '$_SESSION[company_name]', $this->body);

Upvotes: 1

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

The problem is the square brackets. They define a character group: any character inside will match.

For example, /[company_name]/ matches any of the characters acemnopy_, so any occurrence of them will be replaced.

From str_replace() docs:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().

Since you are only replacing constant strings, I'd recommend str_replace() instead. That assumes the search patterns are plain strings.

Just replace preg_replace() with str_replace() here and remove the regex slashes.

$patterns = array();
$patterns[0] = '[company_name]';
$patterns[1] = '[company_logo]';
$patterns[2] = '[company_address]';
// identical code omitted 
return str_replace($patterns, $replacements, $content);

If you really, really need to use preg_replace(), escape the brackets with \'s.

$patterns = array();
$patterns[0] = '/\\[company_name\\]/'; 
$patterns[1] = '/\\[company_logo\\]/'; 
$patterns[2] = '/\\[company_address\\]/';
// identical code omitted 

Upvotes: 1

Related Questions