PHP - Removing Everything After Last _ In A String
What I want to do is simple:
The string "this_is_an_example.php" should return "this_is_an_" while: "this_is_an_example_filename.php should return "this_is_an_example_" Is there a simple function which can cut off the part after the last _ ? I have been looking and trying several functions, but can't seem to find the right one for this. (the last _ being cut off of course wouldn't be a problem I couldn't live with :-) ) Any help will be greatly appreciated! Similar TutorialsI have the following function, which takes a string with commas in it and attempts remove those commas. The way I have it here is that I use explode to take out the commas, which makes an array, and then iterate through that array to put a string back together without the commas. function tags_to_sort_by( $sortMeta ) { $sortByArray = explode(",", $sortMeta); $sortByCount = count($sortByArray); for ($i = 0; $i < $sortByCount; $i++) { $sortByString += $sortByArray[$i]; } return $sortByString; } What does not work is the following line: $sortByString += $sortByArray[$i]; Somehow that outputs a 0, which I don't understand. It should output something like: arrayItem1 arrayItem2 array3 etc. My question is if there either is an easier way to remove the commas from the original string or what I am doing wrong in this line: $sortByString += $sortByArray[$i]; // I am trying to concatenate each part of the array back into the string. Thanks a lot for help with this! hi im having trouble removing ' from strings
so say
$name = "D'vion";
$newname = str_replace("'","",$name);
but this just returns the same.
thanks matt
Hello Everyone, I am working on a project I pull the field names from the database. I am trying to remove the underscore (_) when the field name is displayed. Does anyone know how I would do that? Here is the code that I am working with Code: [Select] $i = 0; while ($i < mysql_num_fields($fieldnamesquery_result)) { $meta = mysql_fetch_field($fieldnamesquery_result, $i); if (!$meta) { echo "No information available"; } $meta = str_replace("_", " ", $meta); $tablecolumn .= "<p>" . $meta->name . ":<input type='text' name='" . $meta->name . "' id='" . $meta->name . "' /></p>"; $i++; Hello guys, I want to remove part of a string and convert it to a var instead of echoing it out.. How would I do it.. $string = "temp_photo/testing.jpg"; I want to remove temp_photo so the out put should be $filename2 = testing.jpg Please advise.. Thanks, Dan Hey all, I'm using the form 'method="get" action="results.php"' on my search form... Say someone uses my 'Photo search' to search my database for aircraft, and leaves all fields blank. In this case, the only field of the search is 'aircraft'. This will take the user to 'results.php?aircraft='. Is there anyway to remove the sting if there is no search value? So it would just read 'results.php'? This is the code i have so far: Code: [Select] <?php if(isset($_GET['aircraft'])){ $aircraft = $_GET['aircraft']; } if($aircraft==""){ $aircraft = mysql_query("IGNORE aircraft"); } ?> Thanks in advanced! %3$s displays a string of text that always begins with a number followed by a colon (from 1-25 only). 1: 2: 3: etc... Is there a way to remove the number and the colon entirely and leave the rest of the string intact? Code: [Select] function wp_rss( $url, $num_items = -1 ) { if ( $rss = fetch_rss( $url ) ) { if ( $num_items !== -1 ) { $rss->items = array_slice( $rss->items, 0, $num_items ); } //start count $i = 1; foreach ( (array) $rss->items as $item ) { printf( '<div title="%2$s"><strong>'.$i.'</strong></div><div>%3$s</div>', esc_url( $item['link'] ), esc_attr( strip_tags( $item['description'] ) ), htmlentities( $item['title'] ) ); //increment $i++; } Ashley Hey guys! I found a flush function and it seems to be working well, but sometimes it will cut off characters. It's very strange. Here's my flush function: function out($str) { echo $str."<br />\n"; vbflush(); } function vbflush() { if (ob_get_length()){ @ob_flush(); @flush(); @ob_end_flush(); } @ob_start(); }And I'm calling it like this:out('Waiting 30 seconds until execution');And this is my output: Code: [Select] Waiting 30 seconds until executioAnyone know why? In <div id="chart_rt">%3$s</div> below, it is populated with a string that always begins with a number followed by a colon (from 1: to 25:). I see that ltrim removes characters from the beginning of a string but I don't see how to compensate for the extra character in 10: through 25: function wp_rss( $url, $num_items = -1 ) { if ( $rss = fetch_rss( $url ) ) { echo '<div id="charts">'; if ( $num_items !== -1 ) { $rss->items = array_slice( $rss->items, 0, $num_items ); } //start count $i = 1; foreach ( (array) $rss->items as $item ) { printf( '<div id="chart_lt">'.$i.'</div><div id="chart_rt">%3$s</div>', esc_url( $item['link'] ), esc_attr( strip_tags( $item['description'] ) ), htmlentities( $item['title'] ) ); //increment $i++; } echo '</div>'; } else { _e( 'An error has occurred, which probably means the feed is down. Try again later.' ); } } Hello, I have this XML file I am parsing and I have hit a small formatting issue that I can't seem to get around.
Here is what the the output of the RSS looks like.
<description><![CDATA[<div style='text-align:left;'>Exit ramp closed. <br/><b>Current Status:</b> Open<br/><b>Affected Lanes:</b> Exit Ramp<br/><b>Dates:</b> Wednesday, May 28 - Thursday, May 29<br/><b>Days Closed:</b> <font color='#808080'>S</font><font color='#808080'>M</font><font color='#808080'>T</font><font color='#FF0000'><b>W</b></font><font color='#FF0000'><b>T</b></font><font color='#808080'>F</font><font color='#808080'>S</font> 20:00 PM - 6:00 AM</div>]]></description>Notice at the first is "Exit ramp closed." There is nothing before it but, for some weird reason when I parse it. It is on a new line like so, notice it should be up there with "Incident" but, it is dropped down below it. Incident: Exit ramp closed. Current Status: Open Affected Lanes: Exit Ramp Dates: Wednesday, May 28 - Thursday, May 29 Days Closed: SMTWTFS 20:00 PM - 6:00 AMThis is how it is formated in the td cell. <td style='{$td2Style}'><strong>Incident:</strong> {$incident_data_desc}</td>\n";So as you can see above, there is nothing before it that would cause it to break to a new line both in the table or in the RSS. So how can I remove that first return only is that is on the same line with it and not below it. I have tried this and a couple of other things like trim with no luck. $description = $item->description; $incident_data_desc = str_replace("\r", '', $description );Note, I only need that first one removed, the others are fine. I can do it but it will remove all the breaks and I only want to remove that first one that is causing the line to be on a new line. Any suggestions? -Thanks Hello, Any help would be great. I'm filtering and rss feed and to create a new feed with some <item>'s removed. Here is a snippet from the source file. <item> <title><h1>Indians, Pacers and Colts attendance is only part of story</h1></title> <link>http://www.newsweek.com/the-score/2010/07/29/indians-pacers-and-colts-draw-similar-sized-crowds/PARAMS/post/21385</link> <description></description> </item> <item> <title><h1>Declining attendance forcing Speedway to make changes</h1></title> <link>http://www.newsweek.com/declining-attendance-forcing-speedway-to-make-changes/PARAMS/article/21369</link> <description></description> </item> <item> <title><h1>Three issues that could derail Indy's 2012 Super Bowl</h1></title> <link>http://www.newsweek.com/the-score/2010/07/27/three-issues-that-could-derail-indys-2012-super-bowl/PARAMS/post/21341</link> <description></description> </item> I'm wanting to use the link tag to detect the item that need to be removed for the new rss feed. All <item>with <link> that contain http://www.newsweek.com/the-score/ as the beginning of the link need to be filtered out. Here is my code so far. <?php echo '<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:media = "http://search.yahoo.com/mrss"> <channel> <title>CLE Calendar</title> <description>CLE Calendar</description> <language>en-us</language> <pubDate>June 14, 2010</pubDate> <lastBuildDate>June 14, 2010</lastBuildDate> <ttl>15</ttl>'; ?> <?php $rss = new SimpleXMLElement('http://www.newsweek.com/mobile-app/rss/feed?rssId=18&premium=false', null, true); ?> <?php foreach ($rss->channel->item as $items): ?> <item> <title><?php echo '<h1>' . $items->title . '</h1>'; ?></title> <link><?php echo $items->link; ?></link> </item> <?php endforeach; ?> </channel> </rss> Thanks in advance, MK This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=321479.0 I have a string of mixed Japanese or Chinese and Western characters and I would really like to leave the western characters and remove the others. Is there any way to detect which UTF-8 characters are Japanese/Chinese and to remove them? I have tried to use this which I found on another thread but my version of PHP (5.3) will not allow the /u in the following Code: [Select] echo "<BR>".preg_replace('/[^\u4E00-\u9FFF]+/', '', $string); I have tried using various combinations of /p (these, plus others) Code: [Select] echo "<BR>".preg_replace('/\p{Bopomofo}+/u', '', $string); echo "<BR>".preg_replace('/\p{Hiragana}+/u', '', $string); and the /x{} option tells me the numbers are to large Code: [Select] echo "<BR>".preg_replace('/[^\x{4E00}-\x{9FFF}]+/', '', $string); My string for this example is this but any combination of western and Japanese/Chinese characters are possible in the title. 2011.12.06 19:00-20:00 / ふくいちライブカメラ (Live Fukushima Nuclear Plant Cam) | Uploaded: 06 Dec 2011 Thanks for any help. Hi, I am trying to make some adjustments to uploadify.php which comes with the latest version of uploadify (3.0 beta), so that it works with a session variable that stores the login username and adds it to the path for uploads. Here is uploadify.php as it currently looks: Code: [Select] <?php session_name("MyLogin"); session_start(); $targetFolder = '/songs/' . $_SESSION['name']; // Relative to the root if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; $targetFile = rtrim($targetPath,'/') .'/'. $_FILES['Filedata']['name']; // Validate the file type $fileTypes = array('m4a','mp3','flac','ogg'); // File extensions $fileParts = pathinfo($_FILES['Filedata']['name']); if (in_array($fileParts['extension'],$fileTypes)) { move_uploaded_file($tempFile,$targetFile); echo '1'; } else { echo 'Invalid file type.'; } } echo $targetFolder; ?> I added Code: [Select] echo $targetFolder; at the bottom so that I could make sure that the string returned was correct, and it is, i.e. '/songs/nick'. For some reason though, uploads are not going to the correct folder, i.e. the username folder, but instead are going to the parent folder 'songs'. The folder for username exists, with correct permissions, and when I manually enter Code: [Select] $targetFolder = '/songs/nick';all works fine. Which strikes me as rather strange. I have limited experience of using php, but wonder how if the correct string is returned by the session variable, the upload works differently than with the manually entered string. Any help would be much appreciated. It's the last issue with a website that was due to go live 2 days ago! Thanks, Nick This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=326004.0 Hello all, I'm trying to change the end of a javascript call based on the end of the url string. The common part of all the url strings is sobi2Id=, I'm trying to do this with strstr but am having no luck. I'm new to php so my syntax knowledge is terrible! at the moment i've got Code: [Select] <?php $url = $_SERVER['REQUEST_URI']; $tag = strstr ($url, 'sobi2Id='); echo $tag; ?> but this returns an unexpected T_STRING, expecting ',' or ';' Can anyone debug this? I may well be being really silly! Hey there, Thanks for taking the time to read my thread. My issue is that I can't think of a way to edit a XML file using PHP's XML functionality and then assign the edited contents to a string instead of saving the file. Because my issue is that I have to edit the XML file based upon a string brought from a remote location then give it back to that remote location using a string again, to be exact I am doing it via Linux command line utilizing SSH2. This is what I managed to complete on my own. function CheckIVMPConfig($ServerID) { global $Panel; if(is_numeric($ServerID) && $this->IsValidServer($ServerID)) { // We select the game server that the FTP account was created for. $Servers = mysql_query("SELECT * FROM control_servers WHERE server_id = '".mysql_real_escape_string($FTPAccount['ftp_server'])."'"); $Server = mysql_fetch_array($Servers); // Here we select the Box ID that the game server is on. $Boxs = mysql_query("SELECT * FROM control_machines WHERE machine_id = '".$Server['server_machine']."'"); $Box = mysql_fetch_array($Boxs); // Now we select the required package for the box. $Packages = mysql_query("SELECT * FROM control_packages WHERE package_id = '".$Server['server_package']."'"); $Package = mysql_fetch_array($Packages); // Retrive the file. $Config = $CProtocol->exec("cat /home/{$Server['server_id']}/{$Package['package_config']}"); $Parse = SimpleXMLElement($Config); foreach($Parse as $Entry) // loop through our books { if($Entry->port != $Server['server_port']) { // edit the value } else if($Entry->maxplayers > $Server['server_slots']) { // edit the value } } } } hey guys im trying to find a string inside a string which could be made up of different things eg... {$test}, {$test1}, {$test2} etc (but the varable inside could be called anything hence maybe using regex im not sure?) is this possible?...i hope you guys understand....thanks
In PHP Version 8.0 shows error as : In previous versions of PHP it does not show any error. Please resolve the issue. Ok... I had typed this post out ONCE already and when I clicked REFRESH IMAGE to get a diff captcha it ERASED MY POST LMAO this is not my night.... What I need help with is probably more simple then I can even think right now - ive been digging at this for 3 hrs now and im out of time for the night I have a DB Record storing ID's between PIPES | when the initial entry is made in DB it stores it like so |47| NOTE: the number could be different these are ID's number doesnt matter its just between Pipes When the second entry is added its added like so |47||67| say we have a total of 5 Entries |47||67||82||55||69| I need to find ID 82 in that string and it has to be between Pipes Find 82 in data between | and return that ID 82 I am putting between pipes because the ID's can be duplicate digits in different lengths so say I have 8 as my ID and down the string i have another id as 88 -- I cant possibly find the correct ID without some sort of seperation character so i used Pipes soo my end goal is the ability to search and if true or false do action if ($result == $find_id){ echo "ID is there"; }else{ echo "NOT THERE -- Adding it"; } Any help is appreciated guys Thanks SangrelX |