Removing last chars from the string

We don't know the length of the sting
We only know how many chars to be removed from string.
$q=substr($q,0,(strlen($q)-3));
Above code will remove last 3 chars from the string $q.
Some time we develop Query where we don't know how many items are there in the list. For example let us see this query.
SELECT * FROM `table_name` WHERE student_id IN ( 1,2,3,4)
To our original query we may add variable part like this
$query1="SELECT * FROM table_name WHERE student_id "; 
$query2= " IN ( 1,2,3,4) ";
$query=$query1.$query2; 
To generate this query we may have to loop through a for loop or any other loop and generate the variable part of the query string with one extra coma ( , ) at the end .
To remove the extra one char at the end we will use like this.
$query=substr($query,0,(strlen($query)-1));
This is in use for our search query generation string tutorial
We used These two string functions
strlen to know the length of the string substr to remove part of the string

Example 2: Extracting the Last 4 Characters of a String

We can easily extract the last few characters of a string using substr() by providing a negative offset:

$string = "Hello, World!";
$last_chars = substr($string, -4);
echo $last_chars; // Outputs: rld!

Example 3: Extracting the Last Word from a Sentence

This example demonstrates extracting the last word from a sentence using strrpos() and substr():

$sentence = "PHP is a popular scripting language";
$last_word = substr($sentence, strrpos($sentence, ' ') + 1);
echo $last_word; // Outputs: language

Example 4: Removing the Last Character Conditionally

You can remove the last character only if it is a specific value (e.g., period):

$sentence = "This is a sentence.";
if (substr($sentence, -1) == '.') {
    $sentence = substr($sentence, 0, -1);
}
echo $sentence; // Outputs: This is a sentence

String Functions first letter of every word to capitalize by using ucwords Change all alphabetic chars to lowercase Checking all lower case or upper case chars in a string
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer