What I'm trying to achieve is to collect all font-families into an array from a string based on the 'font-family', so for example
$string="
Hi <span style=\"font-family: Arial \">text in Arial</span>
<br />
A new line
<br />
Hello again <span style=\"font-family:Courier ; font-size:12px;\"> text in courier font</span>
<br />
Ready
";
$array_fonts = preg_match_all(????);
So the $array_fonts should contain the values 'Arial' and 'Courier'.
Is this possible?
You can try this one. Explanation in the code in comments. If you are really intrested, I could explain the pattern too.
$string = ' Hi <span style="font-family: Arial ">text in Arial</span>
<br />
A new line
<br />
Hello again <span style="font-family:Courier ; font-size:12px;"> text in courier font</span>
<br />
Ready
';
//Initialize the result array
$fonts = array();
//Create a new DOMDocument and load the HTML string
$Dom = new \DOMDocument();
$Dom->loadHTML($string);
//Create a new DOMXPath
$xpath = new \DOMXPath($Dom);
//Get the spans
$spans = $xpath->query("//span");
//Iterate through spans
foreach ($spans as $span) {
//Get the style attribute
$style = $span->getAttribute('style');
if ($style) {
//If span has style, init an array for matches
$matches = array();
//Get the font family into the matches array
preg_match('@font-family(\s*):(.*?)(\s?)("|;|$)@i', $style, $matches);
if (!empty($matches[2])) {
//If found font family, trim it, and put it into the result array
$fonts[] = trim($matches[2]);
}
}
}
var_dump($fonts);
Output:
array (size=2)
0 => string 'Arial' (length=5)
1 => string 'Courier' (length=7)