Alex Vasilyev
Alex Vasilyev

Reputation: 141

How to convert HTML "class" attribute to css selector using php language?

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 )

Upvotes: 3

Views: 363

Answers (5)

arkascha
arkascha

Reputation: 42885

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

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

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);

Upvotes: 1

Christoph
Christoph

Reputation: 281

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):

Upvotes: 1

amedv
amedv

Reputation: 388

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);

Upvotes: 2

Twisty
Twisty

Reputation: 30883

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.

Upvotes: 1

Related Questions