Skip to content

Instantly share code, notes, and snippets.

@imvaskii
Created May 16, 2017 07:01
Show Gist options
  • Save imvaskii/f101fb4a06dbb8a35c0958c0df6e2172 to your computer and use it in GitHub Desktop.
Save imvaskii/f101fb4a06dbb8a35c0958c0df6e2172 to your computer and use it in GitHub Desktop.
WordPress: Functions to fetch one liner content from post_content
<?php
if ( ! function_exists( 'twr_get_progressive_line') ) {
/**
* Returns proper line string from given $string content by progressively matching each line of the given html blob
* @param string $content
* @param integer $nth_line nth line to scan of given string
* @param integer $scanned_chars characters scanned
* @return mixed|null|string
*/
function twr_get_progressive_line( $content, $nth_line=1, $scanned_chars=0 ) {
$line_end_pos = twr_strpos( $content, PHP_EOL, $nth_line );
if ( false == $line_end_pos ) {
return NULL;
}
$excerpt_limit_pos = $scanned_chars + 100; // 100 is excerpt_limit_offset,
// if currently scanned line is greater than excerpt limit then return
if ( $line_end_pos > $excerpt_limit_pos ) {
return strip_tags( substr( $content, 0, $line_end_pos ) );
} else {
$nth_line++;
return twr_get_progressive_line( $content, $nth_line, $line_end_pos );
}
}
}
if ( ! function_exists( 'twr_strpos' ) ) {
/**
*
* finds position of nth occurance of search string
*
* @param string $needle string being searched
* @param string $haystack
* @param int $offset nth occurance of needle
*
* @return int or false if not found
*
*/
function twr_strpos( $haystack, $needle, $offset ) {
$arr = explode( $needle, $haystack );
switch( $offset ) {
case $offset == 0:
return false;
break;
case $offset > max( array_keys( $arr ) ):
return false;
break;
default:
return strlen( implode( $needle, array_slice( $arr, 0, $offset ) ) );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment