Showing posts with label PHP SUBSTR. Show all posts
Showing posts with label PHP SUBSTR. Show all posts

Friday, 2 August 2019

How to get the last character in a string using PHP

  • This can be done by using the substr which will return a part of a string.
  • The sample code below will return the letter f
    $lastChar= substr("abcdef", -1);
    The -1 is negative, the returned string will start at the last character from the end of the string.

[function.file-put-contents]: failed to open stream: File name too long

Error: [<a href=’function.file-put-contents’>function.file-put-contents</a>]: failed to open stream: File name too long
To solve this error you need to rename the filename so that the filename and extention together are no more than 255 characters, an easy way to do this is
$filename=substr($name,0,251).'.pdf';
Note, that we used the character count 251 since 251 + the 4 characters for the extention together add up to 255 characters.

Tuesday, 18 September 2018

Extract the first paragraph text from a web page with PHP

This post looks at how to extract the first paragraph from an HTML page using PHP's strpos and substr functions to find the location of the first <p> and </p> tags and get the content between them.

Using strpos and substr

Assuming the content to extract the paragraph from is in the variable $html (which may have come from a file, database, template or downloaded from an external website), use the following code to work out the position of the first <p> tag, the first </p> tag after that tag, and then get all the HTML between them including the opening and closing tags:
$start = strpos($html, '<p>');
$end = strpos($html, '</p>', $start);
$paragraph = substr($html, $start, $end-$start+4);
Line 1 gets the position of the first opening <p> tag
Line 2 gets the position of the first </p> after the first opening <p>
Line 3 then uses substr to get the HTML. The third parameter is the number of characters to copy and is calculated by subtracting $start from $end and adding on the length of "</p>" so it is included in the extracted HTML.

Converting to plain text

If the extracted paragraph needs to be in plain text rather than HTML, use the following to remove the HTML tags and convert HTML entities into normal plain text:
$paragraph = html_entity_decode(strip_tags($paragraph));

Related posts:

Remove extension from a filename with PHP

If you've got a filename that you need to remove the extension from with PHP, there are a number of ways to do it. Here's three ways, with some benchmarking.

Using pathinfo

The pathinfo() function returns an array containing the directory name, basename, extension and filename. Alternatively, you can pass it one of the PATHINFO_ constants and just return that part of the full filename:
$filename = 'filename.html';
$without_extension = pathinfo($filename, PATHINFO_FILENAME);
If the filename contains a full path, then only the filename without the extension is returned.

Using basename

If the extension is known and is the same for the all the filenames, you can pass the second optional parameter to basename() to tell it to strip that extension from the filename:
$filename = 'filename.html';
$without_extension = basename($filename, '.html');
If the filename contains a full path, then only the filename without the extension is returned.

Using substr and strrpos

$filename = 'filename.html';
$without_extension = substr($filename, 0, strrpos($filename, "."));
If the filename contains a full path, then the full path and filename without the extension is returned. You could basename() it as well to get rid of the path if needed (e.g. basename(substr($filename, 0, strrpos($filename, ".")))) although it's slower than using pathinfo.

Benchmarking

Running each of these in a loop 10,000,000 times on my Mac with PHP 5.4:
pathinfo: 10.13 seconds
basename: 7.87 seconds
substr/strrpos: 6.05 seconds
basename(substr/strrpos): 11.98 seconds
If the filename doesn't contain the full path or it doesn't matter if it does, then the substr/strrpos option appears to be the fastest.
If the filename does contain a path and you don't want the path but do know what the extension you want to remove is, then basename appears to be the fastest.
If the filename contains a path, you don't want the path and you don't know what the extension is, then use the pathinfo() option.

Conclusion

There will be plenty of other ways to do this, and some may be faster. In a lot of cases, the speed probably doesn't really matter that much (the 10 seconds to run pathinfo was 10 million times, after all); the purpose of this post was to show a few ways to remove the extension from the filename with PHP.

Related posts:

Thursday, 30 August 2018

Returns the part of a string before the first occurrence of a character in php

In PHP, what is the simplest way to return the portion of a string before the first occurrence of a specific character?

For example, if I have a string...
"The quick brown foxed jumped over the etc etc."
...and I am filtering for a space character (" "), the function would return "The"
Thanks!

You could do this:
$string = 'The quick brown fox jumped over the lazy dog';
$substring = substr($string, 0, strpos($string, ' '));

But I like this better:
list($firstWord) = explode(' ', $string);

Friday, 26 June 2015

PHP: Trim A String with PHP

<?php
/* 
Example usage: 

$long_string="This is a very long string that I want shortened"; 
$short_string=trimString($long_string, 10); 

echo $short_string;  

Will output "This is..." 
*/ 
function trimString($str, $len) { 
    If(strlen($str)>intval($len)) { 
            return(substr($str,0,($len-3))."..."); 
    } 
    return($str); 
?>

Friday, 5 June 2015

PHP: Create a random password

<?php

/** * The letter l (lowercase L) and the number 1

* have been removed, as they can be mistaken

* for each other. */

function createRandomPassword(){   

$chars = "abcdefghijkmnopqrstuvwxyz023456789";   
$i = 0;   
$pass = '' ; 
while ($i <= 7) {
$num = rand() % 33;     
$tmp = substr($chars, $num, 1);     
$pass = $pass . $tmp;       
$i++;   

return $pass;
}

// Usage$password = createRandomPassword();
echo "Your random password is: $password";
?>

Wednesday, 3 June 2015

Remove Last Character from String in PHP

This is a very common PHP question of HOW TO remove last character from string in PHP. Find below some ways how to delete last character from string in PHP.
    <?php 
    // method 1 - substr and mb_substr
    substr($string, 0, -1);
    mb_substr($string, 0, -1);
     
    // method 2 - substr_replace
    substr_replace($string, '', -1);
     
    // method 3 - rtrim
    // it trims all specified characters from end of the string
    rtrim($string, ".");
    ?>

Tuesday, 2 June 2015

Monday, 23 February 2015

PHP: Generate an alpha-numeric password salt

<?php
/**
 * This function generates an alpha-numeric password salt (with a default of 32 characters)
 * @param $max integer The number of characters in the string
 *
 */
function generateSalt($max = 32) {
$baseStr = time() . rand(0, 1000000) . rand(0, 1000000);
$md5Hash = md5($baseStr);
if($max < 32){
$md5Hash = substr($md5Hash, 0, $max);
}
return $md5Hash;
}

//Usage:
/*
echo "Salt with 32 characters:\n";
echo generateSalt() . "\n";
echo "Salt with 5 characters:\n";
echo generateSalt(5) . "\n";
*/
?>

PHP: Detect browser language

If your website is multilingual, it can be useful to detect the browser language to use this language as the default. The code below will return the language used by the client’s browser.

function get_client_language($availableLanguages, $default='en'){
 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

  foreach ($langs as $value){
   $choice=substr($value,0,2);
   if(in_array($choice, $availableLanguages)){
    return $choice;
   }
  }
 } 
 return $default;

Friday, 19 September 2014

PHP characters limit 10 for display

<?php
echo substr(strip_tags("welcome to this new style editor for checking php code at online"), 2, 10);
?>


substr: Return "world" from the string: 
syntax: substr(string,start,length).

If the start parameter is a negative number and length is less than or equal to start, length becomes 0.

Parameter Description
   string        Required. Specifies the string to return a part of
   start Required. Specifies where to start in the string
  • A positive number - Start at a specified position in the string
  • A negative number - Start at a specified position from the end of the string
  • 0 - Start at the first character in string
   length Optional. Specifies the length of the returned string. Default is to the end of the string.
  • A positive number - The length to be returned from the start parameter
  • Negative number - The length to be returned from the end of the string

PHP: Count occurrences of a character in a String in PHP

<?php
$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero
for($i="0"; $i<strlen($text); $i=$i+1){
    
    if(substr($text,$i,1)==$searchchar){
    
       $count=$count+1;
    }
}
echo $count
?>
This will count how many times the character "e" occurs in that text (Welcome to PHP).