swan
swan

Reputation: 2599

PHP read content and do a preg_match

I am trying to get the font-family only if the selector is starting with @font-face, and breaks if selector is not starting with @font-face, but below do not seem to work.

CSS file content:

@font-face {
  font-family: 'someFonts'; 
}

@font-face {
  font-family: 'someotherFonts';    
}

.style {
  font-family: 'someFonts';
}

PHP:

$content = file_get_contents($file->uri);
if (!preg_match('#@font-face {([^;]+);#i', $content, $matches)) {
  break;
}

$fonts = array();
if (preg_match_all('#font-family:([^;]+);#i', $content, $matches)) {
  foreach ($matches[1] as $match) {
    if (preg_match('#"([^"]+)"#i', $match, $font_match)) {
      $fonts[] = $font_match[1];
    }
    elseif (preg_match("#'([^']+)'#i", $match, $font_match)) {
      $fonts[] = $font_match[1];
    }
  }
}

Any hint is very much appreciated. Thanks

Upvotes: 0

Views: 1215

Answers (3)

Kaii
Kaii

Reputation: 20540

I think you have a misunderstanding about how preg_match() works. Your if() condition always evaluates true, because there actually is @font-face { .. } somewhere in the file.

You can use preg_match_all() to find all defined font-families inside a @font-face selector like this:

$fonts = array();
$content = file_get_contents($file->uri);

if( preg_match_all('=@font-face\s*{.*font-family: (.*)[\s|;].*}=isU', 
       $content, 
       $matches) ) {
    $fonts = array_merge($fonts, $matches[1]);
}

print_r($fonts);

Result:

Array ( 
       [0] => 'someFonts' 
       [1] => 'someotherFonts' 
) // the second "someFonts" from your class ".style" is not included in the list!

Upvotes: 1

Teneff
Teneff

Reputation: 32158

You can try with regex:

#@font-face\s*\{\s*(([^:]+)\s*:\s*([^;]+);\s*)+?\s*}#i

it will match any @font-face declaration (single or multiline)

Upvotes: 0

crazyphoton
crazyphoton

Reputation: 623

Are you sure its not working? I have no problem with the following code -

$content = "@font-face {
  font-family: 'someotherFonts';    
}

.style {
  font-family: 'someFonts';
}";

if (!preg_match('#@font-face {([^;]+);#i', $content, $matches)) {
  echo "didnt find match";
}
else{
    print_r($matches);
}

Does the above code work for you?

Possible issues could be 1. Its not reading correctly from the file. Try echoing $content. 2. It works, and there was some oversight while checking. Try echoing $matches in an else block.

Upvotes: 1

Related Questions