The script below pulls a summary of the content in $description and if a period is found in the first 50 characters, it returns the first 50 characters and the period. However, the flaw is, when no period exists in the content, it just returns the first character.
function get_cat_desc($description){
$the_description = strip_tags($description);
if(strlen($the_description) > 50 )
return SUBSTR( $the_description,0,STRPOS( $the_description,".",50)+1);
else return $the_description;}
I'd like to make it so that if no period is found, it returns up until the first empty space after 50 characters (so it doesn't cut a word off) and appends "..."
Your best bet is to use regular expression. This will match your $description up to $maxLength (2nd argument in function) but will continue until it finds the next space.
function get_cat_desc($description, $max_length = 50) {
$the_description = strip_tags($description);
if(strlen($the_description) > $max_length && preg_match('#^\s*(.{'. $max_length .',}?)[,.\s]+.*$#s', $the_description, $matches)) {
return $matches[1] .'...';
} else {
return $the_description;
}
}
I think it just needs to be a little more complicated:
function get_cat_desc($description){
$the_description = strip_tags($description);
if(strlen($the_description) > 50 ) {
if (STRPOS( $the_description,".",50) !== false) {
return SUBSTR( $the_description,0,STRPOS( $the_description,".",50)+1);
} else {
return SUBSTR( $the_description,0,50) . '...';
}
} else {
return $the_description;
}
}
Try something like this:
$pos_period = strpos($the_description, '.');
if ($pos_period !== false && $pos_period <= 50) {
return substr($the_description, 0, 50);
} else {
$next_space = strpos($the_description, ' ', 50);
if ($next_space !== false) {
return substr($the_description, 0, $next_space) . '...';
} else {
return substr($the_description, 0, 50) . '...';
}
}
use substr_count to find it and then do substr(,0,50)
Related
I have a project where I need some basic boolean search in pure PHP. It means I have plain strings I want to offer some simple boolean search on them. No database or other indexing engine is involved, so please don't refer to MySQL boolean search or lucene.
At the end something like the following code should print contains and not found.
$search = 'foo -bar "must have" -"must not have"';
$contentFound = 'This is some foo text you must have.';
$contentNotFound = 'This is some bar text you must have.';
if ($this->booleanSearch($contentFound, $search)) {
echo 'contains';
} else {
echo 'not found';
}
if ($this->booleanSearch($contentNotFound, $search)) {
echo 'contains';
} else {
echo 'not found';
}
For a simple implementation you could just split the criteria (taking into account the quotes) and iterate over each criterion to see whether it matches or not:
function booleanSearch($content, $search) {
$criteria = str_getcsv($search, ' ');
while ($criteria) {
$not = false;
$q = array_shift($criteria);
if (substr($q, 0, 2) === '-"') {
$not = true;
while (substr($q, -1) != '"') {
$q .= " " . array_shift($criteria);
}
$q = substr($q, 2, -1);
}
else if (substr($q, 0, 1) === '-' && strpos($q, ' ') === false) {
$not = true;
$q = substr($q, 1);
}
$found = strpos($content, $q) !== false;
if ($found === $not) {
return false;
}
}
return true;
}
How can I check if a sentence contains a word. I used names sentence and word instead of string and substring expressly. For example:
for sentence
$s = "Ala makota, a kot ma przesrane";
calling function
checkIfContains("kota",$s)
returns false.
But for
checkIfContains("makota",$s)
returns true.
If you're looking to match only full words, you'll need a regular expression to accomplish this. Try the following:
<?php
function checkIfContains( $needle, $haystack ) {
return preg_match( '#\b' . preg_quote( $needle, '#' ) . '\b#i', $haystack ) !== 0;
}
You need strpos.
if (strpos($s, 'kota') !== false) {
}
Or if you insist..
function checkIfContains($needle, $haystack) {
return (strpos($haystack, $needle) !== false);
}
For full words you could consider regex:
if (preg_match('/\bkota\b/i', $s)) { }
I'd use explode to separate the string into an array based on a character (" " in this case).
function checkIfContains($toTest, $toCheck)
{
// Check if length of either string is zero for validation purposes
if(strlen($toTest) == 0 || strlen($toCheck) == 0)
{
return false;
}
$exploded = explode(" ", $toCheck);
foreach($exploded as $word)
{
if($word == $toTest)
{
// Found a match, return true!
return true;
}
}
// None matched, return false
return false;
}
You can try :
function checkIfContains($needle, $haystack) {
// Remove punctuation marks
$haystack = preg_replace('/[^a-zA-Z 0-9]+/', '', $haystack);
// Explode sentence with space
$haystack = explode(' ', $haystack);
// Check if $needle exist
return in_array($needle, $haystack);
}
$string = "Ala makota, a kot ma przesrane";
checkIfInString("makota", $string);
function checkIfInString($needle, $haystack) {
$delimiters = ' ,.';
return in_array($needle, explode($haystack, $delimiters);
}
you can try like :
if(strpos($s,"kota") !== false){
echo true;
}
or :
function checkIfContains($string, $letter){
return strpos($string, $letter) !== false;
}
I need to remove all characters from any string before the occurrence of this inside the string:
"www/audio"
Not sure how I can do this.
You can use strstr to do this.
echo strstr($str, 'www/audio');
Considering
$string="We have www/audio path where the audio files are stored"; //Considering the string like this
Either you can use
strstr($string, 'www/audio');
Or
$expStr=explode("www/audio",$string);
$resultString="www/audio".$expStr[1];
I use this functions
function strright($str, $separator) {
if (intval($separator)) {
return substr($str, -$separator);
} elseif ($separator === 0) {
return $str;
} else {
$strpos = strpos($str, $separator);
if ($strpos === false) {
return $str;
} else {
return substr($str, -$strpos + 1);
}
}
}
function strleft($str, $separator) {
if (intval($separator)) {
return substr($str, 0, $separator);
} elseif ($separator === 0) {
return $str;
} else {
$strpos = strpos($str, $separator);
if ($strpos === false) {
return $str;
} else {
return substr($str, 0, $strpos);
}
}
}
You can use substring and strpos to accomplish this goal.
You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.
I thought to do a preg_count for each "/<[a-z0-9]+>/i" and then count if exists the same number with the closed tags ie: "/</[a-z0-9]+>/i"
But I am not too sure. How would you count all opened tags and check if exists all closed tags?
Ps. i don't need to check for attribute and for xml /> single close tag. I just need a count on plain simple html tag
Thanks
I wrote this handy functions. I think it could be faster if I search both opened/closed tags within one preg_match_all but as this it's more readable:
<?php
//> Will count number of <[a-z]> tag and </[a-z]> tag (will also validate the order)
//> Note br should be in the form of <br /> for not causing problems
function validHTML($html,$checkOrder=true) {
preg_match_all( '#<([a-z]+)>#i' , $html, $start, PREG_OFFSET_CAPTURE );
preg_match_all( '#<\/([a-z]+)>#i' , $html, $end, PREG_OFFSET_CAPTURE );
$start = $start[1];
$end = $end[1];
if (count($start) != count($end) )
throw new Exception('Check numbers of tags');
if ($checkOrder) {
$is = 0;
foreach($end as $v){
if ($v[0] != $start[$is][0] || $v[1] < $start[$is][1] )
throw new Exception('End tag ['.$v[0].'] not opened');
$is++;
}
}
return true;
}
//> Usage::
try {
validHTML('<p>hello</p><li></li></p><p>');
} catch (Exception $e) {
echo $e->getMessage();
}
Note if you need to catch even h1 or any other tag with numbers you need to add 0-9 within pattern of preg
The proper way to validate HTML is using a HTML parser. Using Regexes to deal with HTML is very wrong - see RegEx match open tags except XHTML self-contained tags
My case
function checkHtml($html) {
$level = 0;
$map = [];
$length = strlen($html);
$open = false;
$tag = '';
for($i = 0; $i < $length; $i ++) {
$c = substr($html, $i, 1);
if($c == '<') {
$open = true;
$tag = '';
} else if($open && ($c == '>' || ord($c) == 32)) {
$open = false;
if(in_array($tag, ['br', 'br/', 'hr/', 'img/', 'hr', 'img'])) {
continue;
}
if(strpos($tag, '/') === 0) {
if(!isset($map[$tag.($level-1)])) {
return false;
}
$level --;
unset($map[$tag.$level]);
} else {
$map['/'.$tag.$level] = true;
$level ++;
}
} else if($open) {
$tag .= $c;
}
}
return $level == 0;
}
ok, one solution would be:
function open_tags($page)
{
$arr=array();
$page // your html/xml/somthing content
$i=0;
while ($i<strlen($page))
{
$i=strpos($page,'<',$i); //position of starting the tag
$end=strpos($page,'>',$i); //position of ending the tag
if(strpos($page,'/')<$end) //if it's an end tag
{
if (array_pop($arr)!=substr($page,$i,$end-$i)); // pop the last value inserted into the stack, and check if it's the same as this one
return FALSE;
}
else
{
array_push($arr,substr($page,$i,$end-$i)); // push the new tag value into the stack
}
}
return $arr;
}
this will return opened tags by order, or false if error.
edit:
function open_tags($page)
{
$arr=array();
$page // your html/xml/somthing content
$i=0;
while ($i<strlen($page))
{
$i=strpos($page,'<',$i); //position of starting the tag
$end=strpos($page,'>',$i); //position of ending the tag
if($end>strpos($page,'<',$i))
return false;
if(strpos($page,'/')<$end) //if it's an end tag
{
if (array_pop($arr)!=substr($page,$i,$end-$i)); // pop the last value inserted into the stack, and check if it's the same as this one
return FALSE;
}
else
{
array_push($arr,substr($page,$i,$end-$i)); // push the new tag value into the stack
}
}
return $arr;
}
I have to test if a string begins with 00 or with +.
pseudocode:
Say I have the string **0090** or **+41**
if the string begins with **0090** return true,
elseif string begins with **+90** replace the **+** with **00**
else return false
The last two digits can be from 0-9.
How do I do that in php?
You can try:
function check(&$input) { // takes the input by reference.
if(preg_match('#^00\d{2}#',$input)) { // input begins with "00"
return true;
} elseif(preg_match('#^\+\d{2}#',$input)) { // input begins with "+"
$input = preg_replace('#^\+#','00',$input); // replace + with 00.
return true;
}else {
return false;
}
}
if (substr($str, 0, 2) === '00')
{
return true;
}
elseif ($str[0] === '+')
{
$str = '00'.substr($str, 1);
return true;
}
else
{
return false;
}
The middle condition won't do anything though, unless $str is a reference.
if (substr($theString, 0, 4) === '0090') {
return true;
} else if (substr($theString, 0, 3) === '+90') {
$theString = '00' . substr($theString, 1);
return true;
} else
return false;