Problem with preg_match

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
like_duh44
Forum Commoner
Posts: 63
Joined: Sat Jul 26, 2003 6:57 pm

Problem with preg_match

Post by like_duh44 »

I have a template file with tags (i.e {L_WELCOME} and {L_LOGIN}). I want to have these replaced with certain text. For example, the {L_WELCOME} would be replaced by whatever is in $lang['welcome'] and with {L_LOGIN} it would be $lang['login']. So, basically, whatever is after the L_. I have this code to get that, but it is failing to find any matches. Any suggestions?

Code: Select all

<?php
function template($index)
{
	$code_lines = explode("\n", $index);

	for ($i = 0;$i < sizeof($code_lines);$i++)
	{
		if (preg_match('(\{L_(.*?)\})', $code_lines[$i], $m))
		{
			preg_replace($m[0], $lang[$m[1]], $code_lines[$i]);
		}
	}

	$code = implode("\n", $code_lines);
	return $code;
}

?>
like_duh44
Forum Commoner
Posts: 63
Joined: Sat Jul 26, 2003 6:57 pm

Post by like_duh44 »

Ok, so I have this, I know its finding the strings right, but it's not replacing them correctly. Any suggestions?

Code: Select all

<?php

function template($code)
{
	global $lang;
	$code_lines = explode("\n", $code);

	for ($i = 0;$i < sizeof($code_lines);$i++)
	{
		if (preg_match('({L_/(.*)/i})', $code_lines[$i], $m))
		{
			str_replace($m[0], $lang['$m[1]'], $code_lines[$i]);
		}
	}

	$code = implode("\n", $code_lines);
	return $code;
}
?>
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

The main problem you have is that you are not returning str_replace to a variable. Also str_replace is case sensitive so using string replace to essentially try to replace WELCOME with $lang['welcome'] won't work.

Lastly, preg_match stops at the first match of pattern so if your line consisted of "{L_WELCOME} to my site do you want to {L_LOGIN}" then only the {L_WELCOME} would be replaced.

I haven't tested it, but you could try the code below.

Code: Select all

function template($code)
{
   global $lang;
   $code_lines = explode("\n", $code);
   $n_code_lines = count($code_lines);

   for ($i = 0;$i < $n_code_lines;$i++)
   {
      if (preg_match_all('/\{L_(.*?)\}/i', $code_lines[$i], $m, PREG_SET_ORDER))
      {
	      $n_matches = count($m);
	      
	      for ($j = 0; $j < $n_matches; $j++)
	      {
	         $code_lines[$i] = str_replace($m[$j][0], $lang[strtolower($m[$j][1])], $code_lines[$i]);
          }
      }
   }

   $code = implode("\n", $code_lines);
   return $code;
}
Post Reply