1

I have the pattern to get selectors of css code which are .classes, #ids and html tags. I used preg_match to sort them into an array just the name of the selector.

what happened is I get only the first selector twice, once with opened parentheses and again without.

This is the $contect:

body{ color: black; } .class_class { color: #fff; font: tahoma; } #awesome_id{ }

and this is the results:

Array
(
    [0] => body{
    [1] => body
)

this is the code:

<?php 
#Patterns
    $selectors  = "/(\.?\#?-?[_a-zA-Z]+[_a-zA-Z0-9-]*\s*)\{/";
#Sort
    preg_match($selectors, $content, $_selectors);
?>
<pre>
<?php
    print_r($_selectors);
?>
</pre>

what i want -according to the content- is for the result to be like this

Array
(
    [0] => body
    [1] => .class_class
    [2] => #awesome_id
)
1
  • Consider using a DOM parser instead. Commented Apr 12, 2014 at 12:29

1 Answer 1

1

You can use this regular expression ~{(.*?)}~

<?php

$str='body{ color: black; } .class_class { color: #fff; font: tahoma; } #awesome_id{ }';
$str = preg_replace("~{(.*?)}~s","", $str);
$arr = array_filter(explode(' ',$str));
print_r($arr);

OUTPUT :

Array
(
    [0] => body
    [1] => .class_class
    [3] => #awesome_id
)

Demo

enter image description here

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

6 Comments

this wont work if there's no space between closing bracket and next selector. If you put " " as second parameter in preg_replace it should work even in this case.
@Dexa, Currently the regex is working as per the OP's requirement , If you want to modify , feel free to edit my answer. :)
Naah, I wont edit it, just thought of mentioning that small thing that could help out.
If I had break line between selectors that won't work.
@AbdullahSalma, I have added the s modifier , See the code . So it will match for line breaks too. $str = preg_replace("~{(.*?)}~s","", $str);
|

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.