PHP - Substr Question And Truncating A Variable
$to = $notifyemail;
$from = "xxx@xxx.com"; $subject = "[ $rawticket ] Random $notifytype Notification"; Currently the output is an email with a total of 15 numbers, i.e. SUBJECT: [ 000000001718989 ] Random $notifytype Notification I want to remove the 0's Would something like this work or is this not possible? "[ (substr($rawticket,9)) ] Random $notifytype Notification"; Similar TutorialsHello, I am trying to use the php function string substr ( string $string , int $start [, int $length ] ) to remove trailing zero's in the DB from the price displayed on the page. Currently using the code below I get this for output - $27.9500 <?php echo $row['prodprice']; ?> I would like to get this $27.95. So I tried using the string substr ( string $string , int $start [, int $length ] ) like this - <?php echo substr("$row['prodprice']",0,5); ?> but I receive t string errors and such using variations of this. Can someone please explain to me what I am doing wrong and give me some pointers on how to fix this? Thanks Code: [Select] echo("<p class=\"commentboxContainer\"><table width=100% border=0> <tr> <td bgcolor=\"#EEE\"><strong><p class=fltlft>$name </strong>says:</p></td> </tr> </table> <table width=100% border=0 bgcolor=\"#EEE\"> <tr> <td width=40%><img src=../images/Icons/People/Anonymous.png width=64 height=64 border=1 /></td> <td width=60%>$comment',0,6</td> </tr> </table> <table width=100% border=0> <tr> <td bgcolor=\"#EEE\" ><p class=fltlft><em>$email</em></p></td> </tr> <tr> <td bgcolor=\"#EEE\" ><p class=fltlft>added on $time</p></td> </tr> </table></p><br>"); Here's my echo statement for displaying comments by users. I want to add a substr (); function to limit the amount of characters of the $comment field. That way if a user makes a long comment it doesn't push the page down. I tried putting it after the echo (); but that didn't work. I also tried putting it before $comment and that didn't even work. I know that if I make two separate echo statements, this can be done, but the field "$comment" is displayed within a table that is part of the original echo statement, so what do I do? If I were to split this variable in half: Code: [Select] $one = none:0 Using this bit of code: function cut($string) { $string = substr($string, strrpos($string, ':')); $string = str_replace(':', '', $string); return $string; } Is it possible to get the part of the string that comes after the : in $one? EDIT: I suppose I could add another : at the end of the string and get the position of the last occurrence, but I'm curious if their is an easier method. Hello. First I'd like to say that I know my way around pretty good but I am not a veteran PHP programmer so talk to me like I'm stupid please Ok... I have a simple chat script set up that will only be used by a few people. I figured out how to truncate the chat when someone logs out, but I can't figure out how to truncate only if ALL users log out. Can someone lead me in the right direction? Thanks I have a line in a php email that is .....
$message .= '<table role="presentation" width="640" style="width:640px;" cellpadding="0" cellspacing="0" border="0" align="center"><tr><td align="center" bgcolor="#EEEEEE" background="https://safebuy.nz/images/background.png" valign="top" style="background: url("https://safebuy.nz/images/background.png") center / cover repeat #EEEEEE;">'; But when it arrives in email it reads..... <table role="presentation" width="640" style="width:640px;" cellpadding="0" cellspacing="0" border="0" align="center"><tr><td align="center" bgcolor="#EEEEEE" background="http://safebuy.nz/images/background.png" valign="top" style="background: url(" http:="" safebuy.nz="" images="" background.png?)="" center="" cover="" repeat="" #EEEEEE;?=""> So I get no background in my email. The rest of email sends fine.
Where have I gone wrong. Hi all I am populating a List menu with values from Mysql table. The values are populated correctly. Once a selection is made and upon submit when I display POST submit values using print_r($_POST) the result is correct only when the value do not contain spaces. For example if the list selection is "One" the $_POST[sel] value is correct. But if the selection is "Two Three" it is only first part before space. How do I get it to give complete value as in the list. Thanks and Regards SKN Hi all, I am relatively new to coding but wondered if someone can helpe me with this. I currently have a PHP file which outputs text that has been entered into a text box and saved. The original output code was this: if ( $this->theme->conf->item_description AND $this->doc->data->dmdescription ) : <?php echo $this->doc->data->dmdescription;?> but I want the text that shows to be truncated to say, 100 characters plus '...' so I came up with the following... <?php $someText = ($this->doc->data->dmdescription);?> <?php echo(substr($someText, 0,100)).'...'; ?> However it shows nothing. I guess $someText is bing linked to dmdescription rather than the text within dmdescription? Any ideas greatly appreciated! bplumb strings from a field(type: VARCHAR(4000)) are being truncated at 255 characters. Apparently this is how varchars work(how is that useful?). I've found these two solutions on the internet but neither of them seemed to work. first, some people thought it might be a php.ini thing, so I put this at the top of my php file: Code: [Select] ini_set ( 'mssql.textlimit' , '65536' ); ini_set ( 'mssql.textsize' , '65536' ); that didn't work, so other people suggested using the text field type instead but these two queries return nothing, so I must be doing something wrong or this just isn't the answer: Code: [Select] $bquery="SELECT CONVERT(TEXT,description) FROM table WHERE userID='$row[userID]'"; $bquery="SELECT CAST(description AS TEXT) FROM table WHERE userID='$row[userID]'"; I have a full-text RSS component for Joomla that I was trying to modify. I wanted to be able to truncate the article to a given number of words and place a link at the end for the rest of the article. I need help figuring out how to add a link to the end of the source article. Added this script to the post.php file. It sort of works but the "$ending" tag doesn't seem to function since there is no "..." appended to the end of articles posted, when I tested it. public function truncate($text, $length = 200, $ending = '...', $exact = true, $considerHtml = false) { if ($considerHtml) { // if the plain text is shorter than the maximum length, return the whole text if (str_word_count(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } // splits all html-tags to scanable lines preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $total_length = str_word_count($ending); $open_tags = array(); $truncate = ''; foreach ($lines as $line_matchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output if (!empty($line_matchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>) if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) { // do nothing // if tag is a closing tag (f.e. </b>) } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) { // delete tag from $open_tags list $pos = array_search($tag_matchings[1], $open_tags); if ($pos !== false) { unset($open_tags[$pos]); } // if tag is an opening tag (f.e. <b>) } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { // add tag to the beginning of $open_tags list array_unshift($open_tags, strtolower($tag_matchings[1])); } // add html-tag to $truncate'd text $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character $content_length = str_word_count(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length+$content_length> $length) { // the number of characters which are left $left = $length - $total_length; $entities_length = 0; // search for html entities if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { if ($entity[1]+1-$entities_length <= $left) { $left--; $entities_length += str_word_count($entity[0]); } else { // no more characters left break; } } } $truncate .= substr($line_matchings[2], 0, $left+$entities_length); // maximum lenght is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // if the maximum length is reached, get off the loop if($total_length>= $length) { break; } } } else { if (str_word_count($text) <= $length) { return $text; } else { $truncate = substr($text, 0, $length - str_word_count($ending)); } } // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurance of a space... $spacepos = strrpos($truncate, ' '); if (isset($spacepos)) { // ...and cut the text in this position $truncate = substr($truncate, 0, $spacepos); } } // add the defined ending to the text $truncate .= $ending; if($considerHtml) { // close all unclosed html-tags foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } } return $truncate; } I have attached the whole file as well if you want to see the rest. This part of the script has the function that originally automatically added the link to the source article: if($link_original==1){ if(strlen($ret->fullText)) $ret->fullText.="<p><a href='". $item->link."' target='_blank'>".$text_link_original."</a></p>"; else $ret->introText.="<p><a href='". $item->link."' target='_blank'>".$text_link_original."</a></p>"; } The problem is that it gets truncated with the rest of the article now. what im trying to d is substr a table name just to get the fisrt character so i can use it as an AS...example FROM news AS n $table = "news"; $as = substr($table, 0, 1); sigular named tables are fine...but if the table is named something like this news_comments and have many underscores i want it to return nc...what is the best way to achieve this please? Is it possible to get substr to end on a word boundry instead of halfway through a word? Code: [Select] $txt = "The cat goes splat on my bumper mat"; echo substr($txt, 0, 120); //this can be around 12 chars so doesnt need to be exactly 12 chars I have a directory list using variables Folder/ and sub folders with /Folder/, what i need to do is replace the beginning slash if there is one. I'm using a recursive command and if i use substr for example: subtr("$variable", 1); it will always remove the first character. What I need is an if statement or something to check to make sure it is a slash. ok so i wan to use substr but i gives me Warning: substr() expects parameter 2 to be long, string given in C:\xampp\htdocs\ede\index.php on line 48 here the code Code: [Select] <?php include "staff/scripts/connect.php"; $query = mysql_query("SELECT * FROM headlines ORDER BY id DESC LIMIT 3"); $rows = mysql_fetch_assoc($query); $author = stripslashes($rows['author']); $date = stripslashes($rows['date']); $picture = stripslashes($rows['picture']); $headline = stripslashes($rows['headline']); mysql_close(); ?> <h2 class="boxtitle">Latest Headlines</h2> <?php do{ ?> <div id="boxhome"> <img src="staff/headlineimg/<?php echo $rows['picture']; ?>" width="100px" height="90px" class="boximg"></img> <div class="boxtitle1"> <font color="#A61E0A"><strong><?php echo $rows['title']?></strong></font><br> <?php echo substr(0,$headline,6)?> </div> </div> <?php }while($rows = mysql_fetch_assoc($query))?> </div> I have front page and page for news, and i wonna to set, on front page to show news but only 100 characters, and on news page to be all text, i done that with substr($news, 0, 100); but i have proble, when i have in $news text like this: Code: [Select] Hi everyone. <b>Bold</b>now, subsrt count <b> and </b> like characters, how can i escape that <b> </b>, <u> </u> and other? Hello,
A not so experienced PHP-user here. For my school assignment, I have to make the following:
"Stolwijkstraat 8" has to be shortened into SW with use of SUBSTR and STRTOUPPER.
My question:
1. How can I be able to use SUBSTR and STRTOUPPER in the same line?
2. How can I be able to remove everything in the line ''Stolwijkstraat 8", on behalf of ''S'' and ''w''?
A quick response would be greatly appreciated.
Kind regards.
Hi guys, I would like to ask your help on how to trim the output (title). for example the title is "php freaks rocks" it should be "php freaks..." Thanks.. Code: [Select] <?php $Url_Path = ""; $data_dir = "" ; $images_dir =$Url_Path."/images/"; $rel_dir = ""; //Database Setting //You must change these values in order to run this script //These value are not visible in the output page source $host = ""; //Server Name $user= ""; //Username $password= ""; //Password $database=""; //Photopost database name or forum database name //Display Setting (Changes to fit your page) $q_switch = "latest"; // "random" or "most_views" or "latest" $limit = 3; //number of image to show // CSS Setting (optional) $class_photopost = ""; $class_gallery = "gallery"; // ************************************************************************* // ************************************************************************* ///////////don't edit below this line if you are too afraid to kill the code////////////// // ---------------------- THESE FUNCS FROM pp-inc ----------------- function mysql_query_eval( $query, $database ) { global $Globals; $mysql_eval_error=""; $mysql_eval_result = mysql_query($query, $database) or $mysql_eval_error = mysql_error(); if ($mysql_eval_error) { if ( $Globals{'debug'} == 1 ) { $letter = "An error was encountered during execution of the query:\n\n"; $letter .= $query."\n\n"; $letter .="The query returned with an errorcode of: \n\n$mysql_eval_error\n\n"; $letter .= "If you need assistence or feel this is a 'bug'; please report it to our "; $letter .= "support forums at: http://www.techimo.com/forum/f27/index.html\n\n"; $letter .= "To turn off these emails, set \$debug=0 in your config-inc.php file."; $email = $Globals{'adminemail'}; $email_from = "From: ".$Globals{'adminemail'}; $subject="Subject: ".$Globals{'webname'}." MySQL Error Report"; $subject=trim($subject); mail( $email, $subject, $letter, $email_from ); } elseif ( $Globals{'debug'} == 2 ) { dieWell( "MySQL error reported!<p>Query: $query<p>Result: $mysql_eval_error<p>Database handle: $database" ); exit; } return FALSE; } else { return $mysql_eval_result; } } function get_ext( $filename ) { $photolen = strlen($filename); $RetVal = substr( $filename, $photolen-3, $photolen); return $RetVal; } function get_filename($filename) { // strip off the last 4 $len = strlen( $filename )-4; $RetVal = substr( $filename, 0, $len); return $RetVal; } // ---------------------- THESE FUNCS FROM pp-inc ----------------- // Connecting, selecting database $link = mysql_connect ("$host", "$user", "$password") or die ('I cannot connect to the database.'); mysql_select_db ("$database")or die("Could not select database"); // Here is the hacked up display_gallery($q_switch) $catquery=""; if ( IsSet($cat) ) { $querya="SELECT catname FROM photopost_categories WHERE id=$cat"; $catq = mysql_query_eval($querya,$link); $catr = mysql_fetch_array($catq); $catname = $catr['catname']; mysql_free_result($catq); $queryb = "SELECT id FROM photopost_categories WHERE parent='$cat' ORDER BY catorder ASC"; $boards = mysql_query_eval($queryb,$link); $cnt=0; while ( $row = mysql_fetch_array($boards, MYSQL_ASSOC)) { $catqid = $row['id']; if ( $cnt == 0 ) { $cnt=1; $catquery .= "$catqid"; } else { $catquery .= ",$catqid"; } } mysql_free_result($boards); } // Connecting, selecting database // Selecting method and Perform SQL query switch ($q_switch) { case "most_views": if ( !IsSet($cat) ) { $group_title = "Most Popular Images - All Categories"; $query = "SELECT id,user,userid,cat,title,bigimage,views FROM photopost_photos WHERE bigimage!='' AND approved='1' $exclude_cat ORDER BY views DESC LIMIT $limit"; } else { $query = "SELECT id,user,userid,cat,title,bigimage,views FROM photopost_photos WHERE bigimage!='' AND approved='1' $exclude_cat AND cat in ($catquery) ORDER BY views DESC LIMIT $limit"; $group_title = "Most Popular Images - $catname"; } break; case "latest": if ( !IsSet($cat) ) { $group_title = "Most Recent Images - All Categories"; $query = "SELECT id,user,userid,cat,title,bigimage,views FROM photopost_photos WHERE bigimage!='' AND approved='1' $exclude_cat ORDER BY date DESC LIMIT $limit"; break; } else { $group_title = "Most Recent Images - $catname"; $query = "SELECT id,user,userid,cat,title,bigimage,views FROM photopost_photos WHERE bigimage!='' AND approved='1' $exclude_cat AND cat in ($catquery) ORDER BY date DESC LIMIT $limit"; break; } break; default: if ( !IsSet($cat) ) { $group_title = "Random Images - All Categories"; $query = "SELECT id,user,userid,cat,title,bigimage,views FROM photopost_photos WHERE bigimage!='' AND approved='1' $exclude_cat ORDER BY RAND() DESC LIMIT $limit"; break; } else { $group_title = "Random Images - $catname"; $query = "SELECT id,user,userid,cat,title,bigimage,views FROM photopost_photos WHERE bigimage!='' AND approved='1' $exclude_cat AND cat in ($catquery) ORDER BY RAND() DESC LIMIT $limit"; break; } break; } $i = 1; $e = 2; $col_val = $column; $result = mysql_query_eval($query,$link) or die("Query failed"); print "<ul class=\"".$class_gallery."\"> "; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { $photo_name = get_filename( $line['bigimage'] ); print "<li>"; $theext = get_ext( $line['bigimage'] ); $thecat = $line['cat']; $temp_user = ($line["userid"]); $filepath = "$data_dir"."$thecat/thumbs/$photo_name.$theext"; $image_stats = getimagesize( $filepath ); $width = $image_stats[0]; $height = $image_stats[1]; $rel_path = "$rel_dir"."$thecat/thumbs/$photo_name.$theext"; print "<a class=\"".$class_photopost."\" href=\"$Url_Path"."showphoto.php?photo=".$line['id']. "\" title=\"".$line["title"]."\">"; if ( file_exists( $rel_path ) ) print "<img src='$filepath' alt='$filepath' width='$width' height='$height' /></a>"; else print "<img src='".$images_dir."nothumb.gif' alt='$filepath' width='$width' height='$height' /></a>"; if ($q_switch == "most_views") { print "<br />".$line["title"]."<br />".$line["views"]." views"; print "</a>"; } else { print "<br /> <a class=\"".$class_photopost."\" href=\"$Url_Path"."showphoto.php?photo=".$line['id']. "\" title=\"".$line["title"]." ".$line["views"]." views\"> ".$line["title"]."<br />".$line["views"]." views"; print "</a></li>"; } } print " </ul> "; // Closing connection mysql_close($link); // mysql_close($db_link); ?> Ok, I'm stumped on this one. I'm looking to strip html code from the following output: Code: [Select] <?php echo substr($f7,0,60); ?> How do I insert the strip_tags into that statement? $num = 27; $first_digit = substr($num, 0); $last_digit = substr($num, -1); echo $first_digit; //this returns 27 echo $last_digit; //this returns 7 In the above example why is the first echo statement returning the full number whereas the second returns the last digit? (I know why the last digit is returned in the second the real question is why wouldn't the first return 2?) Edited June 23 by TechnoDiverActually.. I'm assuming I use substr, but feel free to correct me if there's a better way. I have an ever changing list that I need to knock the from numbers off of. The numbers can be different lenghts, such as.. 1. item number 1 12. item number 12 101. item number 101 How do I remove the number, period and blank space for each item, since the length of the number may always differ? Thank you! |