Shuffle text inside HTML elements - php

I´m trying to shuffle articles with the PHP-shuffle function and with the Simple HTML Parser.
For example, this is my content:
<p>This is my article.</p>
<h2>This is a subheading</h2>
<p>This is an paragraph with an image inside it <img src="http://image.jpg">
</p>
The output should be something like this:
<p>article is This my .</p>
<h2>This subheading is a</h2>
<p>is an with an image paragraph inside This it <img src="http://image.jpg"></p>
However, using the Simple HTML DOM parser, I find it difficult to prevent the images from being shuffeled because they sometimes are placed inside paragraphs.
This is my current script. I feel like it is way to complicated, and it sometimes doesn't output the correct result.
Hopefully someone can help me.
$tags = 'p, ul, ol, blockquote, h1, h2, h3, h4, h5, h6, h7';
$html = str_get_html( $html );
/**
* Loop through HTML and set output
*/
foreach( $html->find( $tags ) as $article ) {
$element = $article->outertext;
$array = $article;
$tag = $article->tag;
$innerHTML = '';
// Nested paragraphs
foreach ( $array->find('p') as $el ){
$word_array = preg_replace( "#[\s]+#", " ", $el->innertext );
$words = explode( " ", $word_array );
$w = '';
shuffle( $words );
foreach ( $words as $word ){
$w .= $word . ' ';
}
$innerHTML .= $el->innertext = $w;
}
// List items
foreach ( $array->find('li') as $el ){
$word_array = preg_replace( "#[\s]+#", " ", $el->innertext );
$words = explode( " ", $word_array );
$w = '';
shuffle( $words );
foreach ( $words as $word ){
$w .= $word . ' ';
}
$innerHTML .= $el->innertext = '<li>' . $w . '</li>';
}
// Images
foreach ( $array->find('img') as $el ) {
// Blur image
$src = stripslashes( str_replace( '"', '', $el->src ) );
$new_src = $this->create_blur_image( $src );
// Replace url with base64 encode
$src = $el->src = $new_src;
$innerHTML .= $el->outertext;
}
// Output
if ( $innerHTML ){
$element = $article->innertext = $innerHTML;
} else {
$word_array = preg_replace( "#[\s]+#", " ", $article->innertext );
$words = explode( " ", $word_array );
$w = '';
shuffle( $words );
foreach ( $words as $word ){
$w .= $word . ' ';
}
$element = $article->innertext = $w;
}
$output .= $article->outertext;
}
$html = $output;
return $html;

Use:
function shuffle($text){
$text_array = array_shuffle(explode(" ",$text));
$text_string = implode($text_array," ");
return $text_string;
}

Related

Wordpress Sorting Tag list Alphabets first then numbers

I'm trying to make my list of tags, organized with first letter heads, to show Alphabet (a, b, c, d, etc..) first then numbers and symbols (#,1,2,3 etc..)
here is my code:
<?php $list = '';
$tags = get_tags();
$groups = array();
if( $tags && is_array( $tags ) ) {
foreach ($tags as $tag) {
$first_letter = strtoupper( $firstLetter );
$groups[ $first_letter ][] = $tag;
}
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
usort($letter, 'myComparison');
$list .= "\n\t" . '</ul><h2>' . apply_filters( 'the_title', $letter ) .'</h2>';
$list .= "\n\t" . '</ul><ul id="archiveEach">';
foreach( $tags as $tag ) {
$lower = strtolower($tag->name);
$name = str_replace(' ', ' ', $tag->name);
$naam = str_replace(' ', '-', $lower);
$link = $tag->link;
$list .= "\n\t\t" . '<li>'.$name.'</li>';
}}}}else $list .= "\n\t" . '<p>Sorry, but no tags were found</p>';
print_r( $list);
?>
I've tried to sort using different functionalities, using this
function myComparison($a, $b){
if(is_numeric($a) && !is_numeric($b))
return 1;
else if(!is_numeric($a) && is_numeric($b))
return -1;
else
return ($a < $b) ? -1 : 1;
}
then calling the function using usort($differnentelements, 'myComparison')
I cannot get it to work -- any suggestions would be really greatly appreciated. thanks!

PHP - Is it possible to add a string to a variable?

I would like to make a small change in a code for a table of contents.
I want to add a sign in front of each heading. The character should be recognized as text.
I've tried a few things, but unfortunately I have not found the right variable.
The code comes from a plugin for Wordpress
I have already tried the following variables:
$items
$tic
$find
$replace
$post
Here is the code that prints the list:
if ( $tic->is_eligible($custom_toc_position) ) {
extract( $args );
$items = $tic->extract_headings( $find, $replace,wptexturize($post->post_content) );
$title = ( array_key_exists('title', $instance) ) ? apply_filters('widget_title', $instance['title']) : '';
if ( strpos($title, '%PAGE_TITLE%') !== false ) $title = str_replace( '%PAGE_TITLE%', get_the_title(), $title );
if ( strpos($title, '%PAGE_NAME%') !== false ) $title = str_replace( '%PAGE_NAME%', get_the_title(), $title );
$hide_inline = $toc_options['show_toc_in_widget_only'];
$css_classes = '';
// bullets?
if ( $toc_options['bullet_spacing'] )
$css_classes .= ' have_bullets';
else
$css_classes .= ' no_bullets';
if ( $items ) {
// before widget (defined by themes)
echo $before_widget;
// display the widget title if one was input (before and after titles defined by themes)
if ( $title ) echo $before_title . $title . $after_title;
// display the list
echo '<ul class="toc_widget_list' . $css_classes . '">' . $items . '</ul>';
// after widget (defined by themes)
echo $after_widget;
}
This are the full code of function extract_headings:
public function extract_headings( &$find, &$replace, $content = '' )
{
$matches = array();
$anchor = '';
$items = false;
// reset the internal collision collection as the_content may have been triggered elsewhere
// eg by themes or other plugins that need to read in content such as metadata fields in
// the head html tag, or to provide descriptions to twitter/facebook
$this->collision_collector = array();
if ( is_array($find) && is_array($replace) && $content ) {
// get all headings
// the html spec allows for a maximum of 6 heading depths
if ( preg_match_all('/(<h([1-6]{1})[^>]*>).*<\/h\2>/msuU', $content, $matches, PREG_SET_ORDER) ) {
// remove undesired headings (if any) as defined by heading_levels
if ( count($this->options['heading_levels']) != 6 ) {
$new_matches = array();
for ($i = 0; $i < count($matches); $i++) {
if ( in_array($matches[$i][2], $this->options['heading_levels']) )
$new_matches[] = $matches[$i];
}
$matches = $new_matches;
}
// remove specific headings if provided via the 'exclude' property
if ( $this->options['exclude'] ) {
$excluded_headings = explode('|', $this->options['exclude']);
if ( count($excluded_headings) > 0 ) {
for ($j = 0; $j < count($excluded_headings); $j++) {
// escape some regular expression characters
// others: http://www.php.net/manual/en/regexp.reference.meta.php
$excluded_headings[$j] = str_replace(
array('*'),
array('.*'),
trim($excluded_headings[$j])
);
}
$new_matches = array();
for ($i = 0; $i < count($matches); $i++) {
$found = false;
for ($j = 0; $j < count($excluded_headings); $j++) {
if ( #preg_match('/^' . $excluded_headings[$j] . '$/imU', strip_tags($matches[$i][0])) ) {
$found = true;
break;
}
}
if (!$found) $new_matches[] = $matches[$i];
}
if ( count($matches) != count($new_matches) )
$matches = $new_matches;
}
}
// remove empty headings
$new_matches = array();
for ($i = 0; $i < count($matches); $i++) {
if ( trim( strip_tags($matches[$i][0]) ) != false )
$new_matches[] = $matches[$i];
}
if ( count($matches) != count($new_matches) )
$matches = $new_matches;
// check minimum number of headings
if ( count($matches) >= $this->options['start'] ) {
for ($i = 0; $i < count($matches); $i++) {
// get anchor and add to find and replace arrays
$anchor = $this->url_anchor_target( $matches[$i][0] );
$find[] = $matches[$i][0];
$replace[] = str_replace(
array(
$matches[$i][1], // start of heading
'</h' . $matches[$i][2] . '>' // end of heading
),
array(
$matches[$i][1] . '<span id="' . $anchor . '">',
'</span></h' . $matches[$i][2] . '>'
),
$matches[$i][0]
);
// assemble flat list
if ( !$this->options['show_heirarchy'] ) {
$items .= '<li><a href="#' . $anchor . '">';
if ( $this->options['ordered_list'] ) $items .= count($replace) . ' ';
$items .= strip_tags($matches[$i][0]) . '</a></li>';
}
}
// build a hierarchical toc?
// we could have tested for $items but that var can be quite large in some cases
if ( $this->options['show_heirarchy'] ) $items = $this->build_hierarchy( $matches );
}
}
}
return $items;
}
I tried it like this:
$items = '>'.$items
$tic = '>'.$tic
$find = '>'.$find
.
.
.
Unfortunately, nothing has hit the right place
$ items addressed only the entire list
The other Variables had no effect or led to errors
The extract_headings is creating the list items. This section of the function...
// assemble flat list
if ( !$this->options['show_heirarchy'] ) {
$items .= '<li><a href="#' . $anchor . '">';
if ( $this->options['ordered_list'] ) $items .= count($replace) . ' ';
$items .= strip_tags($matches[$i][0]) . '</a></li>';
}
Should look like this:
// assemble flat list
if ( !$this->options['show_heirarchy'] ) {
$items .= '<li><a href="#' . $anchor . '">>';
if ( $this->options['ordered_list'] ) $items .= count($replace) . ' ';
$items .= strip_tags($matches[$i][0]) . '</a></li>';
}
You can see I've added an extra > inside the hyperlink on the third line. If adding an extra > causes any issues, you can also use >.

Custom Wordpress Excerpt by two paragraphs

I found the answers to limiting the excerpts to only 2 paragraphs or more. However, the code I found only apply to the actual excerpt, not to custom excerpt that I made. I made two excerpts, one for certain posts on front page and another for the posts page. I wanted to add that code to the custom excerpt that I made for the posts page. How do I do that.
Here's my code that I created:
// Create the Custom Excerpts callback
function wpden_excerpt($length_callback = '', $more_callback = '')
{
global $post;
if (function_exists($length_callback)) {
add_filter('excerpt_length', $length_callback);
}
if (function_exists($more_callback)) {
add_filter('excerpt_more', $more_callback);
}
$output = get_the_excerpt();
$output = apply_filters('wptexturize', $output);
$output = apply_filters('convert_chars', $output);
$output = '<p>' . $output . '</p>';
echo $output;
}
// Custom Length
function wpden_mag_len($length) {
return 200;
}
function wpden_more_view($more){
global $post;
return '... <a class="view-article" href="' . get_permalink($post->ID) . '">' . __('', 'wpden') . '</a>';
}
And I called it in my template_post.php:
<?php wpden_excerpt('wpden_mag_len','wpden_more_view'); ?>
The code in question that I wanted to use for my custom wpden_excerpt is either this:
add_filter( 'wp_trim_excerpt', 'my_custom_excerpt', 10, 2 );
function my_custom_excerpt($text, $raw_excerpt) {
if( ! $raw_excerpt ) {
$content = apply_filters( 'the_content', get_the_content() );
$text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
}
return $text;
}
from this site or from the other stack overflow question
$wpse0001_excerpt = get_the_content('');
$wpse0001_excerpt = strip_shortcodes( $wpse0001_excerpt );
$wpse0001_excerpt = apply_filters('the_content', $wpse0001_excerpt);
// Here we choose how many paragraphs do we want to cutthe excerpt at, This part thanks to Clément Malet
$wpse0001_excerpt = "<p>$wpse0001_excerpt</p>";
$wanted_number_of_paragraph = 2;
$tmp = explode ('</p>', $wpse0001_excerpt);
for ($i = 0; $i < $wanted_number_of_paragraph; ++$i) {
if (isset($tmp[$i]) && $tmp[$i] != '') {
$tmp_to_add[$i] = $tmp[$i];
}
}
$wpse0001_excerpt = implode('</p>', $tmp_to_add) . '</p>';
$wpse0001_excerpt = str_replace(']]>', ']]>', $wpse0001_excerpt);
$excerpt_end = ' ' . ' » ' . sprintf(__( 'Read more about: %s »', 'pietergoosen' ), get_the_title()) . '';
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
//$pos = strrpos($wpse0001_excerpt, '</');
//if ($pos !== false)
// Inside last HTML tag
//$wpse0001_excerpt = substr_replace($wpse0001_excerpt, $excerpt_end, $pos, 0);
//else
// After the content
$wpse0001_excerpt .= $excerpt_end;
return $wpse0001_excerpt;
}
return apply_filters('wpse0001_custom_wp_trim_excerpt', $wpse0001_excerpt, $raw_excerpt);
}
endif;
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wpse0001_custom_wp_trim_excerpt');
The thing is that those codes in question apply to the the_excerpt and override the custom excerpt that I made. I tried to format the code like this:
function wpden_excerpt($text = '')
{
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace('\]\]\>', ']]>', $text);
$text = preg_replace('#<script[^>]*?>.*?</script>#si', '', $text);
$text = strip_tags($text, '<p>');
$excerpt_length = 80;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, '[...]');
$text = implode(' ', $words);
}
}
return $text;
}
and called it in the template as
<?php wpden_excerpt('text'); ?>
But it's not working. What was wrong and how do I fix it?
UPDATE
I still need help!!! I tried many different combo of custom excerpt and limiting the excerpt to one paragraph and I wasn't able to do so... Please help!!
Thanks to my brother's help, I was able to edit the code to show two paragraphs for a custom excerpt:
// Create the Custom Excerpts callback
function wpden_excerpt()
{
global $post;
$output = get_the_content();
$wanted_number_of_paragraph = 2;
$tmp = explode ('</p>', $output);
for ($i = 0; $i < $wanted_number_of_paragraph; ++$i) {
if (isset($tmp[$i]) && $tmp[$i] != '') {
$tmp_to_add[$i] = $tmp[$i];
}
}
$output = implode('</p>', $tmp_to_add) . '</p>';
echo $output;
}
and call it in my template file as
<?php wpden_excerpt(); ?>

Foundation Magellan auto generate

I'd like to auto generate magellan on subpages from h3 tags.
For this purpose I tried jameswlane script (https://gist.github.com/jameswlane/f1eabeedf430ef67318d), and I changed only h2 tags to h3. It seems I dont aunderstand this code well.
I thought I only need to paste this code in my header.php file from wordpress theme and it will automatically sweep the DOM content for h3 tags, but it didn't.
Nothing shows up, even an empty div.
Used the followinf line as init:
<?php $tag = 'h3'; $html = get_the_content(); $items = getTextBetweenTags( $tag, $html ); ?>
Can I ask you for an advise in this matter?
<?php
function getTextBetweenTags($tag, $html, $strict=0) {
$dom = new domDocument;
if($strict==1) {
$dom->loadXML($html);
} else {
$dom->loadHTML($html);
}
$dom->preserveWhiteSpace = false;
$content = $dom->getElementsByTagname($tag);
$out = array();
foreach ($content as $item) {
$out[] = $item->nodeValue;
}
return $out;
}
function create_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}
function create_magellan($items){
$output .= '<div data-magellan-expedition="fixed">' . PHP_EOL;
$output .= '<dl class="sub-nav">' . PHP_EOL;
foreach( $items as $item ) {
$output .= '<dd data-magellan-arrival="' . create_slug( $item ) . '">' . $item . '</dd>';
}
$output .= '</dl>' . PHP_EOL;
$output .= '</div>' . PHP_EOL;
add_filter('the_content', 'my_formatter', 99);
echo $output;
}
function my_formatter($content) {
$new_content = '';
$tag = 'h3';
$pattern_full = '{(<' . $tag . '>.*?</' . $tag . '>)}is';
$pattern_contents = '{<' . $tag . '>(.*?)</' . $tag . '>}is';
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($pieces as $piece) {
if (preg_match($pattern_contents, $piece, $matches)) {
$test = $matches[1];
$new_content .= '<a name="'.create_slug($test).'"></a>'.PHP_EOL.'<'.$tag.' data-magellan-destination="'.create_slug($test).'">'.$test.'</'.$tag.'>'.PHP_EOL;
} else {
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
?>
EDIT
Something worked and returned error:
Warning: DOMDocument::loadHTML(): Empty string supplied as input in /www/ilee_www/www/2.goldbaltic/dev.goldbaltic.pl/wp-content/themes/dermiclab_fs/partials/2.Nav/mainNav.php on line 47
the line number 47 in my file is
$dom->loadHTML($html);
from
function getTextBetweenTags($tag, $html, $strict=0) {
$dom = new domDocument;
if($strict==1) {
$dom->loadXML($html);
} else {
$dom->loadHTML($html);
}
$dom->preserveWhiteSpace = false;
$content = $dom->getElementsByTagname($tag);
$out = array();
foreach ($content as $item) {
$out[] = $item->nodeValue;
}
return $out;
}

Want to create a ul li from some comma seperated values

currently i have some comma seperated values like
"oranges, apples, pies"
and i want to turn those into a list like this
oranges
apples
pies
hope anyone can help me here
$data = "oranges, apples, pies";
$data = explode(',', $data);
echo '<ul>';
foreach ( $data as $item ) {
echo '<li>', trim($item), '</li>';
}
echo '</ul>';
[sarcasm=on]
For those who are looking for unmaintainable, hard-to-read code with no complex stuff like arrays and looping through them (yeah, I know, string technically is a kind of array, though it's different from what usually is meant with arrays):
$input = 'oranges, apples, pies';
$output = '';
$output = '<ul><li>';
$inputLength = strlen($input);
$skipSpaces = true;
for ( $n = 0; $n < $inputLength; ++$n ) {
if ( $skipSpaces ) {
if ( $input[$n] === ' ' ) {
continue;
}
$skipSpaces = false;
}
if ( $input[$n] === ',' ) {
$skipSpaces = true;
$output .= '</li><li>';
continue;
}
$output .= $input[$n];
}
$output .= '</li></ul>';
var_dump($output);
$slist = "oranges, apples, pies";
echo "<ul><li>" . str_replace(", ", "</li><li>", $slist) . "</li></ul>";
Will only add none yet mentioned possibilities:
printf(
'<ul><li>%s</li></ul>',
implode(
'</li><li>',
str_getcsv("oranges, apples, pies")
)
);
though str_getcsv is somewhat overkill if you dont have multiple rows and enclosing chars and stuff like that. Can just as well just use explode then.
Yet another possibility:
echo '<ul>';
$tok = strtok("oranges, apples, pies", ',');
while ($tok !== false) {
echo '<li>', trim($tok), '</li>';
$tok = strtok(',');
}
echo '</ul>';
And another one:
$dom = new DOMDocument;
$dom->appendChild(
$dom->createElement('ul')
);
foreach(explode(',', 'oranges, apples, pies') as $fruit) {
$dom->documentElement->appendChild(
$dom->createElement('li', $fruit)
);
}
$dom->formatOutput = TRUE;
echo $dom->saveXml($dom->documentElement);
And a final one:
$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startElement('ul');
foreach(explode(',', 'oranges, apples, pies') as $fruit) {
$writer->writeElement('li', $fruit);
}
$writer->endElement();

Categories