-1

Sorry if my question is being duplicate because I've tried to find similar questionI've got a data column in MySQL which look something like this :

https://i.stack.imgur.com/3VRI9.png

I've created a form which display the address in html using php.

$pdf_content .= '<div style="padding-left:5%">';
$pdf_content .= $company_name.'<br>';
$pdf_content .= '<div id="errorMessage">'.$address.'<br></div>';
//$pdf_content .= 'Add2,<br>';
//$pdf_content .= 'Add3,<br>';
$pdf_content .= $postcode.'<br>';
$pdf_content .= $state.'<br>';
$pdf_content .= $country.'<br>';
$pdf_content .= $mobile_phone.'<br>';
$pdf_content .= '<b>RE: Quotation for 3<sup>rd</sup> party claim vehicle </b>';
$pdf_content .= '</div><br>';

What I wanted to do now is the address which look something like No.43,Jalan Bandar Bahagia,Taman Pinji Mewah 1 , I wanted to separate the second comma which will look something like this

https://i.stack.imgur.com/0OlG3.png

I've tried but still not working

$pdf_content .= $address.'<br>';
    $myList_explode = explode(",",$address);
    for($i=0;$i<sizeof($myList_explode);$i++){
    echo $myList_explode[$i];
    if(($i+1)%2==0){
    echo "</br>";
   }else{
   echo ",";
   }
}

Is possible to do it in php while in MySQL it won't be separated?Thanks in advance.

Shadow
  • 33,525
  • 10
  • 51
  • 64
evasim
  • 109
  • 10

2 Answers2

0

You can try like this...:

$string = 'No.43,Jalan Bandar Bahagia,Taman Pinji Mewah 1';

echo formatString($string);
// No.43,Jalan Bandar Bahagia
// Taman Pinji Mewah 1

function formatString($inputString) {
    $stringToArray = explode(",",$inputString);
    $finalString = "";
    $count = count($stringToArray) - 1;
    foreach($stringToArray as $k => $arr) {
        $addon = ",";
        if($k == 1) {
            $addon = "<br>";
        } 
        if($k == $count) {
            $addon = "";
        }
        
        $finalString .= $arr.$addon;
    }
    
    return $finalString;
}

Basically you create an array from string with explode, loop over it and create a string out of the elements. And since you want to add
after second comma, function adds it if $key == 1 (second key).

JureW
  • 641
  • 1
  • 6
  • 15
  • "Try like this" answers are low value on Stackoverflow because they do very little to educate/empower thousands of future researchers. – mickmackusa Feb 24 '21 at 08:23
0

Consume the leading substring before the second occurring comma, then forget it with \K. Then match the second occurring comma and replace it.

Regex prevents having to write a multi-line solution with a loop.

Code: (Demo)

echo preg_replace('~^[^,]*,[^,]*\K,~', '<br>', $address);

Output:

No.43,Jalan Bandar Bahagia<br>Taman Pinji Mewah 1

My pattern bears some similarity to the pattern in this preg_match() call: https://stackoverflow.com/a/65355441/2943403

mickmackusa
  • 43,625
  • 12
  • 83
  • 136