Jump to content

preg_replace problem


atl_andy

Recommended Posts

Taking a shot that this will be solved.  The following will add (' to the first word in $file.  I need to be able to add ') to the end as well, so ABC will become ('ABC').  However, I can't get it to add (' to all the words.  I tried using g to globally add, but it didn't work. (user error of course)  My thought is to send the results of $str through another for loop to add the ') to the end.  But I'm lost.  Any ideas would be appreciated.

 

<?php
    $file = ("/var/www/html/string.php");
    $lines = file_get_contents($file);

    for ($i=0; $i < count($lines); $i++)
    {
      $str = preg_replace("/^/","(' ",$lines); //I added some spaces for easier reading.
      echo "$str\n";
    }

Link to comment
https://forums.phpfreaks.com/topic/97719-preg_replace-problem/
Share on other sites

Update:  I added m in the regex and it add (' to the beginning of each word in the file.  Now to add it to the end and write the results to a file....

 


<?php
    $file = ("/var/www/html/string.php");
    $lines = file_get_contents($file);

    for ($i=0; $i < count($lines); $i++)
    {
      $str = preg_replace("/^/m","(' ",$lines); //I added the m.
      echo "$str\n";
    }

Link to comment
https://forums.phpfreaks.com/topic/97719-preg_replace-problem/#findComment-500032
Share on other sites

Update #2:

 

<?php
    $file = ("/var/www/html/string.php");
    $lines = file_get_contents($file);

    for ($i=0; $i < count($lines); $i++)
    {
      $str = preg_replace("/^/m","(' ",$lines);

    }

     for ($i=0; $i < count($lines); $i++)
    {
      $sta = preg_replace("/$/m"," ') ",$str);
      echo "$str\n";
    }

Link to comment
https://forums.phpfreaks.com/topic/97719-preg_replace-problem/#findComment-500049
Share on other sites

That's nice.  I had to modify a bit because some items are alpha-numeric with some dashes.

 

The end result was:

 

echo $lines = preg_replace('/([a-z0-9-]+)/i', "('$1');", $lines);

 

 

And it worked perfectly.  Thanks for your help!  I'm using it to parse text files so I can import into sql.

 

One other question....the results are shown in my broswer like:

 

result result result result

result result result result

 

but I need:

 

result

result

result

 

Any suggestions?

Link to comment
https://forums.phpfreaks.com/topic/97719-preg_replace-problem/#findComment-500636
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.