PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 29, 2021

[FIXED] Replacing all occurrences of a string with values from an array

 December 29, 2021     loops, php, phpmyadmin, string     No comments   

Issue

I am parsing a string before sending it to a DB. I want to go over all <br> in that string and replace them with unique numbers that I get from an array followed by a newLine.

For example:

str = "Line <br> Line <br> Line <br> Line <br>"
$replace = array("1", "2", "3", "4");

my function would return 
"Line 1 \n Line 2 \n Line 3 \n Line 4 \n"

Sounds simple enough. I would just do a while loop, get all the occurances of <br> using strpos, and replace those with the required numbers+\n using str_replace.

Problem is that I always get an error and I have no idea what I am doing wrong? Probably a dumb mistake, but still annoying.

Here is my code

$str     = "Line <br> Line <br> Line <br> Line <br>";
$replace = array("1", "2", "3", "4");
$replaceIndex = 0;

while(strpos($str, '<br>') != false )
{
    $str = str_replace('<br>', $replace[index] . ' ' .'\n', $str); //str_replace, replaces the first occurance of <br> it finds
    index++;
}

Any ideas please?

Thanks in advance,


Solution

I would use a regex and a custom callback, like this:

$str = "Line <br> Line <br> Line <br> Line <br>";
$replace = array("1", "2", "3", "4");
$str = preg_replace_callback( '/<br>/', function( $match) use( &$replace) {
    return array_shift( $replace) . ' ' . "\n";
}, $str);

Note that this assumes we can modify the $replace array. If that's not the case, you can keep a counter:

$str = "Line <br> Line <br> Line <br> Line <br>";
$replace = array("1", "2", "3", "4");
$count = 0;
$str = preg_replace_callback( '/<br>/', function( $match) use( $replace, &$count) {
    return $replace[$count++] . ' ' . "\n";
}, $str);

You can see from this demo that this outputs:

Line 1 Line 2 Line 3 Line 4 


Answered By - nickb
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing