Help with a str_replace problem

I have a text file that contains

[http://mydomain.com]

I am using php to convert this text file to html (to then use as an input file for an import function)

So I need to replace the opening [ with <a href=" and the closing ] with "></a>

However my str_replace has a syntax error as I cannot add the closing "

What I have currently is

[php]
$line1 = str_replace (’[’,’,$line1);
[/php]

I cannot reconstruct this string like this so how can I do this?

TIA

Here you go…

Your code answer:
[php]$line1 = str_replace(’[’,’’,$line1);
echo $line1;[/php]

With preg_replace answer:
[php]$pattern = array (’/[/’, ‘/]/’);
$replace = array (’’);
echo preg_replace($pattern, $replace, ‘[http://mydomain.com]’);[/php]

Thanks very much works perfectly.

Feel free to click Karma next to my name.

I have now done a bit more digging through these text files that I need to convert and have found some are in a different format.

They look like

[http://mydomain.com|Link to my website]

and the others look like my original question. I have added a bit to Kevin,s code so it now looks like

[php]
$pattern = array (’/[/’, ‘/]/’);
$replace = array (‘Link’);
echo preg_replace($pattern, $replace, ‘[http://mydomain.com]’);
[/php]

But I now need to change it so that if there is a | in the text then I need to replace the word Link with everything between the | and ] but if there is no | then I need the word Link there. I obviously need an if clause to check for the existence of the | but try as I might I can’t get it to work.

This pattern replacement does have to work multiple times on the input text file as often there is more than one link to be changed.

Any thoughts?

Does the data need to be stored with those characters in the first place? If not, you can just do a search and replace and clean the data.

Kevin,

Unfortunately the text files were created some time ago. I have just over 900 directories with up to 9 text files in each. I need to concatenate and convert the up to 9 text files into one simple HTML file that I can then use as an automated input file to create 900+ Custom Post Types in Wordpress. Some of these text files are a few years old.

The problem is they are not all identical some have a link in and some don’t.

I have now resolved this with some help by using the following code (I hope it helps someone else)

[php]
$output = preg_replace_callback(’#[([^]]+)]#’, function($m)
{
$parts = explode(’|’, $m[1]);
if (count($parts) == 2)
{
return sprintf(’%s’, $parts[0], $parts[1]);
}
else
{
return sprintf(’%1$s’, $m[1]);
}
}, $input);
echo $output;
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service