3

How to convert a string with class into a selector even if it contains many spaces between classes?

Input data:

$html_classes = 'class1    class2  class3 ';

Necessary result:

.class1.class2.class3

This example is not appropriate as there may be many spaces between classes

$result = '.' . str_replace( ' ', '.', $html_classes )
  • 2
    Might consider using Regular Expressions or `explode()` – Twisty Jan 18 '19 at 22:36
  • 1
    Possible duplicate of [php Replacing multiple spaces with a single space](https://stackoverflow.com/questions/2368539/php-replacing-multiple-spaces-with-a-single-space). Don't forget to use `trim()` as well to remove any starting or ending space. – M. Eriksson Jan 18 '19 at 22:40

5 Answers5

2

Just replace all extra spaces to singles first. And run trim() to remove spaces on the beginning and at the end.

$html_classes = 'class1    class2  class3 ';
$html_classes = trim(preg_replace('/\s+/',' ',$html_classes));
$result = '.' . str_replace(' ','.',$html_classes);
amedv
  • 388
  • 1
  • 16
  • 2
    Why not replace directly to `.`? – Don't Panic Jan 18 '19 at 22:48
  • Actually, yes! I'm just tried add extra line to show what is missed in logic. – amedv Jan 18 '19 at 22:51
  • Makes sense. I was just wondering if there was a reason not do do it in one step that I wasn't thinking of – Don't Panic Jan 18 '19 at 22:52
  • May be only in case we can have space (or even few spaces) in the beginning or end of string — then we have to replace all extra spaces to singles first, run trim() on this result and after that replace spaces to dots to avoid extra dots on the beginning result string or unnecessary dots at the end. – amedv Jan 18 '19 at 22:57
1

Try this:

<?php
$html_classes = 'class1    class2  class3 ';
$parts = explode(" ", $html_classes);
$results = "";
foreach($parts as $c){
    if($c != ""){
        $results .= "." . $c;
    }
}
echo $results;
?>

The results I got:

.class1.class2.class3

Hope that helps.

Twisty
  • 30,304
  • 2
  • 26
  • 45
1

My suggestion:

<?php
$html_classes = 'class1    class2  class3 ';
$result = '.' . preg_replace('/\s+/', '.', trim($html_classes));
echo $result;
?>

Regular expressions:

  • \s is a whitespace character.

  • + means one or more occurrences.

PHP (from http://php.net):

Christoph
  • 291
  • 2
  • 7
1

You can do it without any extra trimming or concatenation. Find non-space characters surrounded by zero or more spaces and replace those matches with the non-space portion of the match preceded with a dot.

$html_classes = preg_replace('/\s*(\S+)\s*/', '.$1', $html_classes);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

The answer is as simple as a single regex based replacement call:

<?php
$input = 'class1    class2  class3  ';
$output = preg_replace('/\s*([\w\d]+)\s*/', '.${1}', $input);
print_r($output);

The output obviously is:

.class1.class2.class3
arkascha
  • 41,620
  • 7
  • 58
  • 90