2

My string:

'KCP-PRO;first_name last_name;address;zipcode;country' //for example: 'KCP-PRO;Jon Doe;Box 564;02201;USA'
or
'KCP-SAT-PRO;first_name last_name;address;zipcode;country'

How can i change the first part (KCP-PRO or KCP-SAT-PRO) and change it to (KCP,PRO or KCP,SAT,PRO)? The outcome has to be:

'KCP,PRO;first_name last_name;address;zipcode;country'
or
'KCP,SAT,PRO;first_name last_name;address;zipcode;country'
4
  • 3
    Is this always the format of your string? You could just use a php built in function (str_replace out of the top of my head) to replace the '-' with a ','. Commented Jan 29, 2016 at 10:38
  • there could be a '-' in the address like 'streetname 1-3', so only the '-' in the first field should be replaced Commented Jan 29, 2016 at 10:41
  • It looks like the title for this question in not appropriate to the question Commented Jan 29, 2016 at 10:56
  • what title would you suggest? Commented Jan 29, 2016 at 11:08

2 Answers 2

3

I haven't tried the code myself but I guess this will do the trick

$string = 'KCP-SAT-PRO;first_name last_name;address;zipcode;country';

$stringExploded = explode(';', $string);
$stringExploded[0] = str_replace('-', ',', $stringExploded[0]);
$output = implode(';', $stringExploded);

//output should be KCP,SAT,PRO;first_name last_name;address;zipcode;country

Hope this helps :)

Sign up to request clarification or add additional context in comments.

7 Comments

wouldn't that make the KCP, SAT and PRO seperated fields? Than you get: KCP;SAT;PRO;first_name last_name;address;zipcode;country
The explode will make stringExploded an array of strings, with KCP-SAT-PRO one string in the first index of the array. Then as you can see, he replaces the '-' with ',' for the first index of the array I.E. KCP-SAT-PRO. Then he implodes the array again with ';', which means that he concatenates all fields while adding a ';' character between each pair of fields.
@ponciste Always explain what your code does, if OP knew that this existed he probably wouldn't have asked the question
@Glubus you're right! and thanks for your explaination! P.S: I've just tried the code myself on phptester.com and it worked fine.
I'll try it and when it works (or not) i will let you know. Thanks!
|
1

Or you can use preg_replace_callback function with the following regex

^[^;]*

So your code looks like as

echo preg_replace_callback("/^[^;]*/",function($m){
     return str_replace("-",',',$m[0]);
},"KCP-SAT-PRO;first_name last_name;address;zipcode;country");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.