I'm trying something out but as I'm not versed in PHP it feels like smashing my head against random walls.
I need to alter the output of image tags. I want to replace the img tag for a div with a background image, to achieve sort of this effect.
I'm working around this function, in functions.php. This only takes the full image code and outputs it into the background-image url. I would need to extract the SRC.
function turnItIntoDiv( $content ) {
// A regular expression of what to look for.
$pattern = '/(<img([^>]*)>)/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<div class="full-image" style="background-image: url("$1")"></div>';
// run preg_replace() on the $content
$content = preg_replace( $pattern, $replacement, $content );
// return the processed content
return $content;
}
add_filter( 'the_content', 'turnItIntoDiv' );
Thank you all in advance
Maybe it would by fine to split.
if (preg_match("/img/i",$content))
{
..
$pattern = '/src="([^"]+)"/i';
..
Then you will get exact file name. Height of div should be set.
Whole code - matching all images:
if (preg_match("/img/i",$content))
{
if (preg_match_all('/src[ ]?=[ ]?"([^"]+)"/i',$content,$matches))
{
foreach ($matches[1] as $i => $match)
{
$replacement = '<div class="full-image" style="background-image: url(\'' . trim($match) . '\')"></div>';
$content = preg_replace("~(<img(.*){$matches[0][$i]}[^>]+>)~i",$replacement,$content);
}
}
}
! div height must be set
Related
<?php
$titledb = array('经济管理','管理','others');
$content='经济管理是我们国的家的中心领导力,这是中文测度。';
$replace='<a target="_blank" href="http://www.a.com/$1">$1</a>';
foreach ($titledb as $title) {
$regex = "~\b(" . preg_quote($title) . ")\b~u";
$content = preg_replace($regex, $replace, $content, 1);
}
echo $content;
?>
I was writing a auto link function for my wordpress site and I'm using substr_replace to find the keywords(which are litterally a lot) and replace it with link--I'm doing this by filtering the post content of course.
But in some circumstances, suppose there are posts with titles like "stackoverflow" and "overflow" it turns out to be a mess, the output will look like :
we love<a target="_blank" href="http://www.a.com/stackoverflow">stackoverflow</a>,this is a test。we love <a target="_blank" href="http://www.a.com/stack<a target=" _blank"="">overflow</a> ">stackoverflow,this is a test。
What I want is:
we love<a target="_blank" href="http://www.a.com/stackoverflow">stackoverflow</a>,this is a test。we love stack<a target="_blank" href="http://www.a.com/overflow">overflow</a>,this is a test。
And this is only a test.The production enviorment could be more complicated,like I said there are tens of thousands of titles as keywords need to be found and replaced with a link. So I see these broken links a lot.It happens when a title contains another title.Like title 'stackoverflow' contains another title 'overflow'.
So my question is how to make substr_replace take title 'stackoverflow' as a whole and replace only once? Of course,'overflow' still needs to be replaced somewhere else just not when it is included in another keyword.
Thank you in advance.
To prevent that a search for a word will start replacing inside the HTML code that you already injected for some other word, you could make use of a temporary placeholder, and do the final replacement on those place holders:
$titledb = array('经济管理','管理','others');
// sort the array from longer strings to smaller strings, to ensure that
// a replacement of a longer string gets precedence:
usort($titledb, function ($a,$b){ return strlen($b)-strlen($a); });
$content='经济管理是我们国的家的中心领导力。';
foreach ($titledb as $index => $title) {
$pos = strpos($content, $title);
if ($pos !== false) {
// temporarily insert a place holder in the format '#number#':
$content = substr_replace($content, "#$index#", $pos, strlen($title));
}
}
// Now replace the place holders with the final hyperlink HTML code
$content = preg_replace_callback("~#(\d+)#~u", function ($match) use ($titledb) {
return "<a target='_blank' href='http://www.a.com/{$titledb[$match[1]]}'>{$titledb[$match[1]]}</a>";
}, $content);
echo $content;
See it run on eval.in
I've been putting together my own customly made forum using PHP, and it's coming along astoundingly, but I was trying to figure out if there is a way to check for matching BBCode tags? I have my own arrays set up to replace <b> with [b] and so on, but I want to be able to make sure that the tags will be closed at some point [/b] and not continue to run off of the post and onto the rest of the page.
For example: [b]This is text will show up as [b]This is text, and [b]This is text[/b] will return on the page as <b>This is text</b>
Is there a way to do this, or is there a way in PHP/HTML to 'escape' any opened tags? IE; if no [/b] is in the post, automatically add a </b> onto the end of it.
this is a very simple bbcode parser for your requirement:
function bbcode($data)
{
$input = array(
'/\[b\](.*?)\[\/b\]/is',
'/\[b\](.*?)$/',
);
$output = array(
'<b>$1</b>',
'<b>$1</b>',
);
return preg_replace ($input, $output, $data);;
}
some examples:
bbcode('[b]text[/]');
//returns <b>text</b>
bbcode('[b]text');
//returns <b>text</b>
See the example running here
So here you want to parse out BBCode tags with HTML Tags, here's a small function I found over web that can do your job pretty easily
<?php
/* Simple PHP BBCode Parser function */
//BBCode Parser function
function showBBcodes($text) {
// BBcode array
$find = array(
'~\[b\](.*?)\[/b\]~s',
'~\[i\](.*?)\[/i\]~s',
'~\[u\](.*?)\[/u\]~s',
'~\[quote\](.*?)\[/quote\]~s',
'~\[size=(.*?)\](.*?)\[/size\]~s',
'~\[color=(.*?)\](.*?)\[/color\]~s',
'~\[url\]((?:ftp|https?)://.*?)\[/url\]~s',
'~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
);
// HTML tags to replace BBcode
$replace = array(
'<b>$1</b>',
'<i>$1</i>',
'<span style="text-decoration:underline;">$1</span>',
'<pre>$1</'.'pre>',
'<span style="font-size:$1px;">$2</span>',
'<span style="color:$1;">$2</span>',
'$1',
'<img src="$1" alt="" />'
);
// Replacing the BBcodes with corresponding HTML tags
return preg_replace($find,$replace,$text);
}
// How to use the above function:
$bbtext = "This is [b]bold[/b] and this is [u]underlined[/u] and this is in [i]italics[/i] with a [color=red] red color[/color]";
$htmltext = showBBcodes($bbtext);
echo $htmltext;
?>
I use the following code to pull an image out of a post content
$content = $post->post_content;
$searchimages = '~<img [^>]* />~';
preg_match_all( $searchimages, $content, $pics );
$iNumberOfPics = count($pics[0]);
if ( $iNumberOfPics > 0 ) {
// Your post have one or more images.
echo $pics[0][0];
}
But now I ran into a problem, the output of images is including all kind of classes. I would like to know if it's possible for me to remove
class="anyrandomclass"
from echo $pics[0][0]; so in the end I get an image without any classes. I found arround a few ways with regex but none of those worked :(
I hope It can be resolve. thanks for the help on this
You can make use of this regex..
echo $finalimg = preg_replace('~class=["|\'](.*?)["|\']~',"", $img);
Basically like...
if ( $iNumberOfPics > 0 ) {
echo $finalimg = preg_replace('~class=["|\'](.*?)["|\']~',"", $pics[0][0]);
}
Demonstration
You have to use preg_replace function. Try this:
preg_replace('/class=".*?"/', "", $pics[0][0]);
This will replace all class="anydata" with nothing in $pics[0][0] variable.
newbie to wordpress here.
I'm currently trying to add a fb share button to all images on my blog and have added this to functions.php:
function breezer_addDivToImage( $content ) {
// A regular expression of what to look for.
$pattern = '/(<img([^>]*)>)/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<div class="myphoto">$1Share on Facebook</div>';
// run preg_replace() on the $content
$content = preg_replace( $pattern, $replacement, $content );
// return the processed content
return $content;
}
add_filter( 'the_content', 'breezer_addDivToImage' );
Works well, except for the fact that the permalink isn't translating (It's sharing the php). There is something stupidly simple I know I'm doing wrong. Any help is greatly appreciated.
Cheers!
inside single quotes strings are placed as it is, they are not converted... so you can use dot operator to concatenate the generated permalink... otherwise you need to escape the quotes... the following example uses string conctenation
$replacement = '<div class="myphoto">$1Share on Facebook</div>';
That's because you are writing your PHP code into a string:
$replacement = '<div class="myphoto">$1
<a href="http://www.facebook.com/sharer.php?u=' . get_permalink() . '" class="facebook-share-btn fb-" data-fsb-service="facebook" data-href="' . get_permalink() . '"...
try that
I need of a function in php that extract a description of a site url that don't have meta tag description any idea?
i have tried this function but don't work :
$content = file_get_contents($url);
function getExcerpt($content) {
$text = html_entity_decode($content);
$excerpt = array();
//match all tags
preg_match_all("|<[^>]+>(.*)]+>|", $text, $p, PREG_PATTERN_ORDER);
for ($x = 0; $x < sizeof($p[0]); $x++) {
if (preg_match('< p >i', $p[0][$x])) {
$strip = strip_tags($p[0][$x]);
if (preg_match("/\./", $strip))
$excerpt[] = $strip;
}
if (isset($excerpt[0])){
preg_match("/([^.]+.)/", $strip,$matches);
return $matches[1];
}
}
return false;
}
$excerpt = getExcerpt($content);
Parsing HTML with RegEx is almost always a bad idea. Thankfully PHP has libraries that can do the work for you. The following code uses DOMDocument to extract either the meta description or if one does not exist, the first 1000 characters in the page.
<?php
function getExcerpt($html) {
$dom = new DOMDocument();
// Parse the inputted HTML into a DOM
$dom->loadHTML($html);
$metaTags = $dom->getElementsByTagName('meta');
// Check for a meta description and return it if it exists
foreach ($metaTags as $metaTag) {
if ($metaTag->getAttribute('name') === "description") {
return $metaTag->getAttribute('content');
}
}
// No meta description, extract an excerpt from the body
// Get the body node
$body = $dom->getElementsByTagName('body');
$body = $body->item(0);
// extract the contents
$bodyText = $body->textContent;
// collapse any line breaks
$bodyText = preg_replace('/\s*\n\s*/', "\n", $bodyText);
// collapse any more leftover spaces or tabs to single spaces
$bodyText = preg_replace('/[ ]+/', ' ', $bodyText);
// return the first 1000 chars
return trim(substr($bodyText, 0, 1000));
}
$html = file_get_contents('test.html');
echo nl2br(getExcerpt($html));
You'll probably want to add a little more logic to it, some DOM traversal to try to find the content, or just some snippet near the middle of the text. As it is, this code will probably grab a bunch of unwanted stuff like the top of the page navigation etc.
You should first check if there is meta description available, if yes then display that else search for the <p> tags and display that data as description (you might want to put a limit on length of a paragraph, e.g. if length is less than 30, search for next paragraph). If there is no <p> tag then simply display the title as description (that's how facebook and Digg works)