PHP - String Snippets
Aus Wikizone
Siehe auch[Bearbeiten]
Überflüssige Whitespace entfernen[Bearbeiten]
<?php
$str = 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>
Zeilenumbruch einfügen[Bearbeiten]
string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )
Zeilenenden normalisieren[Bearbeiten]
function normalize($s) {
// Normalize line endings using Global
// Convert all line-endings to UNIX format
$s = str_replace(CRLF, LF, $s);
$s = str_replace(CR, LF, $s);
// Don't allow out-of-control blank lines
$s = preg_replace("/\n{2,}/", LF . LF, $s);
return $s;
}
Text kürzen[Bearbeiten]
Text kürzen / HTML entfernen[Bearbeiten]
function truncateText($text,$characters=500){
$summary = strip_tags($text);
if(strlen($summary) > $characters) {
$summary = substr($summary, 0, $characters); // display no more than 500 chars
$trimToSentence = substr($summary, 0, strrpos($summary, ". ")+1); // and truncate to last sentence
if( strlen( $trimToSentence) > intval($characters/3) ) $summary = $trimToSentence; // use it if not too short
}
$summary = trim($summary);
return $summary;
}
// Beispiel 2
function truncateText($text, $maxlength = 200) {
// truncate to max length
$text = substr(strip_tags($text), 0, $maxlength);
// check if we've truncated to a spot that needs further truncation
if(strlen(rtrim($text, ' .!?,;')) == $maxlength) {
// truncate to last word
$text = substr($text, 0, strrpos($text, ' '));
}
return trim($text);
}
Einsatz in Processwire:
$summary = truncateText($page->body);
echo "
<a href='$page->url'>$page->title</a>
<p class='summary'>$summary</p>
";
Text kürzen HTML belassen[Bearbeiten]
function truncateHtml($text, $length = 100) {
$current_size = strlen($text);
$diff = strlen($text);
$remainder = $current_size - $length;
while($diff > 0 AND $remainder > 0) {
$pattern = "/(.*)[^<>](?=<)/s";
$text = preg_replace($pattern, "$1", $text);
$diff = $current_size - strlen($text);
$current_size = strlen($text);
$remainder = $current_size - $length;
}
// iff $diff == 0 there are no more characters to remove
// iff $remainder == 0 there should removed no more characters
return $text;
}
Auf Wortende kürzen[Bearbeiten]
function limit_words($words, $limit, $append = ' …') {
$limit = $limit+1;
$words = explode(' ', $words, $limit+1);
array_pop($words); // Shorten the array by 1 because that final element will be the sum of all the words after the limit
$words = implode(' ', $words) . $append;
return $words;
}
Auf Satzende kürzen[Bearbeiten]
<?php
function substr_sentence($string, $start=0, $limit=10, $max_char = 600)
{
/* This functions cuts a long string in sentences.
*
* substr_sentence($string, $start, $limit);
* $string = 'A example. By someone that loves PHP. Do you? We do!';
* $start = 0; // we would start at the beginning
* $limit = 10; // so, we get 10 sentences (not 10 words or characters!)
*
* It's not as substr()) in single characters.
* It's not as substr_words() in single words.
*
* No more broken lines in a story. The story/article must go on!
*
* Written by Eddy Erkelens "Zunflappie"
* Published on www.mastercode.nl
* May be free used and adapted
*
*/
// list of sentences-ends. All sentences ends with one of these. For PHP, add the ;
$end_characters = array(
'. ',
'? ',
'! '
);
// put $string in array $parts, necessary evil
$parts = array($string);
// foreach interpunctation-mark we will do this loop
foreach($end_characters as $end_character)
{
// go thru each part of the sentences we already have
foreach($parts as $part)
{
// make array with the new sentences
$sentences[] = explode($end_character, $part);
}
// unfortunately explode() removes the end character itself. So, place it back
foreach($sentences as $sentence)
{
// some strange stuff
foreach($sentence as $real_sentence)
{
// empty sentence we do not want
if($real_sentence != '')
{
// if there is already an end-character, dont place another one
if(in_array(substr($real_sentence, -1, 1), $end_characters))
{
// store for next round
$next[] = trim($real_sentence);
}
else
{
// store for next round and add the removed character
$next[] = trim($real_sentence).$end_character;
}
}
}
}
// store for next round
$parts = $next;
// unset the remaining and useless stuff
unset($sentences, $sentence, $next);
}
// check for max-char-length
$total_chars = 0;
$sentence_nr = 0;
$sentences = array();
// walk thru each member of $part
foreach($parts as $part)
{
// count the string-lenght and add this to $total_chars
$total_chars += strlen($part);
// if $total-chars not already higher then max-char, add this sentences!
if($total_chars < $max_char)
{
$sentences[] = $part;
}
}
// return the shortened story as a string
return implode(" ", array_slice($sentences, $start, $limit));
}
?>
Telefonnummer für Telefonlink konvertieren (nur Zahlen)[Bearbeiten]
// Extract phone number from a string
$telLink = '';
$tel = '07121 / 123-45';
$tel = preg_replace('/[^0-9]/', '', $tel);
$telLink = '<a href="tel:'.$telLink.'" class="button tel">Direkt anrufen</a>';
String als Variablenname[Bearbeiten]
Manchmal möchte man einen String als Variable nutzen, damit PHP den Namen des Strings als Variable Nutzt kann man so arbeiten:
$string = 'meineVariable';
${$string} = Hallo;
echo($meineVariable) // Hallo
Führende Null / Leading Zero[Bearbeiten]
Use sprintf :
sprintf('%08d', 1234567);
Alternatively you can also use str_pad:
str_pad($value, 8, '0', STR_PAD_LEFT); // does not work with negativ value
Zufällige Zeichenkette mit definierten Zeichen erstellen[Bearbeiten]
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randString = substr(str_shuffle($permitted_chars), 0, 10);