Re: Why does this preg_replace function not work?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 5/26/06, Dave M G <martin@xxxxxxxxxxxxx> wrote:
PHP List,

In the code below, I want to take the text within $content, and change
every instance of [h3] into <h3>, and every instance of [/h3] into
</h3>. And then do the same for [em], [/em], [strong], and so on.

However, this code does absolutely nothing to the text stored in content:

$tags = array ("h3", "em", "strong", "hr");
$content = preg_replace("[" . $tags . "]", "<" . $tags . ">", $content);
$content = preg_replace("[/" . $tags . "]", "</" . $tags . ">", $content);

Clearly I've either misunderstood the use of preg_replace(), or regular
expressions, or arrays, despite having looked them up in the PHP online
manual.

I also tried str_replace(), but predictably that did not help. As far as
I understand it, it does not accept arrays.

You want str_replace. It does accept arrays. You put in all the things
you want to replace in one array, and all the things they will be replaced
by into another array and call str_replace:

$from = array('[h3]', '[/h3]');
$to = array('<h3>', '</h3>');
$content = str_replace($from, $to, $content);

This will work if you a list of the tag names. If you want to
generically replace
[anyword] with <anyword>, you'll have to go for preg_replace and regular
expressions.

Rabin

--
http://rab.in

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux