0

I want to do something like:

<?php
$text = "<font style='color: #fff'>";
$replaceandshow = str_replace("<font style=\"?\">", "the font style is ?", $text);
echo $replaceandshow;
?>

For example the ? is color: #fff, but I want that PHP will trace it by itself, Is it possible + If it's possible , How can I do that?

P.S: Someone gave me a code but it's now working, it displays a White page for me.

<?php
$colorstring = "<font style='#fff'>";
$searchcolor = preg_replace('[a-fA-F0-9]{3,6}','[font style=$1]Test[/font]',$colorstring);
echo $searchcolor;

Thanks for helping.

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
OverSpan
  • 99
  • 1
  • 1
  • 11

3 Answers3

1

Since you need to pull basically any attribute out of any HTML you can use php XML parsing to do this.

<?php
$doc=new DOMDocument();
$doc->loadHTML("<html><body>Test<br><font style='color: #fff;'>hellow</font><a href='www.somesite.com' title='some title'>some site</a></body></html>");
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$fonts=$xml->xpath('//font');
foreach ($fonts as $font) {
    echo 'font style = '.$font['style']."<br />";
}

$as=$xml->xpath('//a');
foreach ($as as $a) {
    echo 'href = '.$a['href'] . ' title = ' . $a['title']."<br />";
}
?>

That will return:

font style = color: #fff;
href = www.somesite.com title = some title

You can use a different foreach loop for each HTML tag you need to extract and then output any of the attributes you want.

Answer based on How to extract img src, title and alt from html using php?

Community
  • 1
  • 1
tsdexter
  • 2,911
  • 4
  • 36
  • 59
1

You are getting white page because error reporting is turned off. The error in your code is missing delimiter in preg_replace. And additionally, to use back-referencing you should enclose the expression required to match in parentheses.

preg_replace('/([a-fA-F0-9]{3,6})/','the font style is $1',$colorstring);

shall give the correct output.

You might consider using a more constrictive expression because the current expression is very open to matching other strings like "FFFont". Another thing to note is that the expression may result in output like.

<font style='color: the color is #fff'>

Try:

/<font style='color: #([a-fA-F0-9]{3,6})'>/
Shubham
  • 21,300
  • 18
  • 66
  • 89
0

This will work with simple style attributes:

$text = "<font style='color: #fff'>";
preg_match("/<font style=['\"]([^'\"]+)['\"]>/", $text, $matches);
echo "The font style is ".$matches[1];

For anything more complicated (ex: if it includes quotes), you'll need to use a HTML parser, such as http://www.php.net/manual/en/class.domdocument.php

Tchoupi
  • 14,560
  • 5
  • 37
  • 71