Reputation: 141
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
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
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
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):
preg_replace — Perform a regular expression search and replace. (http://php.net/manual/pl/function.preg-replace.php)
trim — Strip whitespace (or other characters) from the beginning and end of a string. (http://php.net/manual/pl/function.trim.php)
Upvotes: 1
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
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