Home > Mobile >  How to add space between names in string PHP?
How to add space between names in string PHP?

Time:11-18

I'm a student and I'm learning PHP. I have a very long list of names but they are in 1 piece.

Example:

$names = "NathanaelDousaMaxbergenRafaelSteen";

Is there a way to put space between the names?

Is there a function for that?

Thank you!

CodePudding user response:

We can use preg_replace here:

$names = "NathanaelDousaMaxbergenRafaelSteen";
$output = preg_replace("/(?<=[a-z])(?=[A-Z])/", " ", $names);
echo $output;  // Nathanael Dousa Maxbergen Rafael Steen

The regex pattern (?<=[a-z])(?=[A-Z]) will match every position which is preceded by a lowercase letter and followed by an uppercase letter. It replaces with a single space, effectively adding a space before the start of each name.

CodePudding user response:

One way would be a regular expression, which is a little advanced.

Using preg_replace()

Here is an example solution with a regular expression:

$string = "NathanaelDousaMaxbergenRafaelSteen";
echo preg_replace('/([a-z])([A-Z])/', '$1 $2', $string);

The above searches a lower case letter, followed by a capital letter and puts a space between them.
You can play around with this regular expression here (also check the right side for an in-depth explanation):
https://regex101.com/r/cvltMB/1

But please, also learn for yourself

I recommend going to the official manual:
https://php.net/manual/

Visit there everything you need a function for something - it is likely there already or can be combination of several. The comments also help for common tricks and pitfalls.
There is also information about regular expressions. It is a large topic, but good to know. Once you've learned it you will always come back to it.

You can also achieve similar with strtr(), which would be more code to write but also a valid example of just getting to an answer.

Especially learning PHP - just read the manual and see what kind of functions are available. There is a whole section for text manipulation which might inspire you to your own solution. You might get corrected on the best way or whatever, but especially learning there is no wrong way but copying your solution from others.

  • Related