Home > Software engineering >  php get every @media tag from css
php get every @media tag from css

Time:11-19

how to get with php every @media tag from css file like and Move from original file to new file

.socialLinks {display: flex;margin: 16px 0 }
.socialLinks ul {display: flex;list-style: none;margin: 16px 0;padding: 0 }
.socialLinks ul li a {align-items: center;background-color: #fff;border-radius: 50%;color: var(--theme-color-primary);display: flex;flex-direction: column;height: 50px;justify-content: center;margin: 0 14px 0 0;text-decoration: none;width: 50px }
.rtl .socialLinks ul li a {margin: 0 0 0 14px }
@media screen and (max-width: 425px) {.style_outerContainer {padding: 20px 0 0}
.socialLinks ul li a {height: 40px;width: 40px}
}
.style_outer {position: relative }
.style_outer .style_containerImage{height: 400px;padding: 157px 0;position: relative;width: 100% }
@media screen and (min-width: 768px) {.style_out .style_c {bottom: 0;height: auto;position: relative;top: 0;width: 100%} }
.style_overlay {background-image: linear-gradient(to bottom, var(--theme-color-primary), var(--theme-color-gradient));border: 1px solid #979797;height: 100%;left: 0;opacity: .7;position: absolute;top: 0;width: 100% }
.intro {display: flex;flex-direction: column;justify-content: center;margin-bottom: 20px }
.intro p {color: #031d5b;color: hsla(0, 0%, 100%, .59);max-width: 400px;opacity: .85 }
.intro h2 {font-weight: 600;margin-bottom: 16px }

output

@media screen and (max-width: 425px) {.style_outerContainer {padding: 20px 0 0}
.socialLinks ul li a {height: 40px;width: 40px}
}
@media screen and (min-width: 768px) {.style_out .style_c {bottom: 0;height: auto;position: relative;top: 0;width: 100%} }

I want to fetech all @media tags from css file using php

CodePudding user response:

With the function preg_match_all you could determine the lines and the contents starting with @media

preg_match_all("/(@media .*)/", $cssContent, $matches);

Example Output:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(79) "@media screen and (max-width: 425px) {.style_outerContainer {padding: 20px 0 0}"
    [1]=>
    string(122) "@media screen and (min-width: 768px) {.style_out .style_c {bottom: 0;height: auto;position: relative;top: 0;width: 100%} }"
  }
  [1]=>
  array(2) {
    [0]=>
    string(79) "@media screen and (max-width: 425px) {.style_outerContainer {padding: 20px 0 0}"
    [1]=>
    string(122) "@media screen and (min-width: 768px) {.style_out .style_c {bottom: 0;height: auto;position: relative;top: 0;width: 100%} }"
  }
}

Second solution:

$matches = [];
$lines = explode("\n", $cssContent); // lines from css
foreach ($lines as $line) {
    if (strpos($line, "@media") !== false) { // check each line 
        $matches[] = $line;
    }
}
  • Related