Function that trims whitespace and ads punctuation if there is none - php

I am trying to make a function that cuts the white spaces in a string and ads punctuation if there isn't any.
This is my test string:
$test = 'Hey there I am traa la la ';
I want it to turn into this:
$test = 'Hey there I am traa la la.';
Here is the function I have tried:
function test($mytrim){
for($i = 0; $i <= 5; $i++){
if(substr($mytrim, 0, -1) == ''){
$mytrim = substr($mytrim, 0, -1);
}
}
$punct = array(".",",","?","!");
if(!in_array($mytrim, $punct)){ $mytrim .= '.'; }
return $mytrim;
}
It returns this:
$mytrim = 'Hey there I am traa la la. .';
Any ideas why it is not working?

PHP has a built in trim function. as for the punctuations, your code should work fine (appending).
Code sample :
<?php
$testString = " hello world ";
$trimmedString = trim($testString); // will contain "hello world"
$lastChar = substr($trimmedString, strlen($trimmedString)-1); // will be "d"
$punct = array(".",",","?","!");
if(!in_array($lastChar, $punct))
echo $trimmedString.'.'; //will output "hello world."

function test ($string)
{
$string = trim($string);
if ((substr($string, -1)) != ".")
{
$string .= ".";
}
}

function adspunctuation($str)
{
$str = trim($str) . (substr($str, -1)!='.' ? '.' : '');
return $str;
}

Related

How can I create a PHP user defined function that is similar to the str_replace()

<?php
echo my_own_string_replace("world","Peter","Hello world!");
function my_own_string_replace($find, $replace, $string)
{
//Block of codes?
}
?>
This should output: Hello Peter
This should work -
function my_own_string_replace($find, $replace, $string)
{
return implode($replace, explode($find, $string));
}
echo my_own_string_replace("world","Peter","Hello world!");
Output
Hello Peter!
Try this: as you say you can only use strlen() and loop and if-else:
echo my_own_string_replace("world","Peter","Hello world!");
function my_own_string_replace($find, $replace, $string)
{
$total_len = strlen($string);
$str = "";
$new_str = "";
for($i = 0;$i<$total_len;$i++)
{
if($string[$i] == " ")
{
$new_str .= $str." ";
$str = "";
}
else
{ $str .= $string[$i];
if($str == $find)
{
$str = $replace;
}
if($i == ($total_len-1))
$new_str .= $str;
}
}
return $new_str;
}
DEMO:

How to trim all leading/trailing <br> code using php

I am trying to remove all leading and trailing <br> in a string using PHP.
Here is an example
<br><br>
Hello<br>
World<br>
<p>This is a message<br>...</p>
<br><br><br><br>
I want to return
Hello<br>
World<br>
<p>This is a message<br>...</p>
I tried to do the following
echo trim($str, '<br>');
But it does not remove them. How can I remove the new line html code?
Use preg_replace with the beginning ^ and end $ anchors:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/', '', $string);
Or for multiple lines:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', $string);
You could also trim() it multiple times:
while($string !== ($string = trim($string, '<br>'))){}
This function does the job. Also applicable to anything else really.
//remove all leading and trailing occurences of needle ($n) from haystack ($h)
function trimAll($h, $n){
if(!$h = trim($h,$n)){
trimAll($h, $n);
}
return $h;
}
I wrote this function that will do the job a little better as it gives me more flexibility on what characters to remove and when this function by default will first remove the leading/trailing characters in order:
any tabs
any new lines
any
any
any tabs
any new lines
function trimString($str, $myList = array("\t","\n", "<br>","<br />", "\t","\n") ){
if( ! is_array($myList) ){
$charsToTrim[] = $chr;
} else {
$charsToTrim = $myList;
}
foreach($charsToTrim as $chr){
$len = strlen($chr);
$nlen = $len * -1;
while( substr($str, 0, $len) == $chr){
$str = trim(substr($str, $len));
}
while( substr($str, $nlen) == $chr){
$str = trim(substr($str, 0, $nlen));
}
}
return $str;
}
to use
// default use case
echo trimString($message);
or
//remove only one string
echo trimString($message, '<br>'); // remove only the leading training '<br>'
or
//remove more than 1 string in order
echo trimString($message, array('<br>'<br />') );
I hope this helps someone out there :)
$p=array(
'<br><br>',
'Hello<br>',
'World<br>',
'<p>This is a message<br>...</p>',
'<br><br><br><br>'
);
function trimdeluxe($str, $sub)
{
$parts=explode($sub, $str);
for ($x=0; $x<2; $x++) {
foreach ($parts as $i=>$v) {
if (!strlen($v)) {
unset($parts[$i]);
} else {
break;
}
}
$parts=array_reverse($parts);
}
return implode($sub,$parts);
}
foreach ($p as $str) {
print $str . ' -> ' . trimdeluxe($str, '<br>') . "\n";
}

match the first & last whole word in a variable

I use php preg_match to match the first & last word in a variable with a given first & last specific words,
example:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '(.*)' . $last_word .'$/' , $str))
{
echo 'true';
}
But the problem is i want to force match the whole word at (starting & ending) not the first or last characters.
Using \b as boudary word limit in search:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '\b(.*)\b' . $last_word .'$/' , $str))
{
echo 'true';
}
I would go about this in a slightly different way:
$firstword = 't';
$lastword = 'ne';
$string = 'this function can be done';
$words = explode(' ', $string);
if (preg_match("/^{$firstword}/i", reset($words)) && preg_match("/{$lastword}$/i", end($words)))
{
echo 'true';
}
==========================================
Here's another way to achieve the same thing
$firstword = 'this';
$lastword = 'done';
$string = 'this can be done';
$words = explode(' ', $string);
if (reset($words) === $firstword && end($words) === $lastword)
{
echo 'true';
}
This is always going to echo true, because we know the firstword and lastword are correct, try changing them to something else and it will not echo true.
I wrote a function to get Start of sentence but it is not any regex in it.
You can write for end like this. I don't add function for the end because of its long...
<?php
function StartSearch($start, $sentence)
{
$data = explode(" ", $sentence);
$flag = false;
$ret = array();
foreach ($data as $val)
{
for($i = 0, $j = 0;$i < strlen($val), $j < strlen($start);$i++)
{
if ($i == 0 && $val{$i} != $start{$j})
break;
if ($flag && $val{$i} != $start{$j})
break;
if ($val{$i} == $start{$j})
{
$flag = true;
$j++;
}
}
if ($j == strlen($start))
{
$ret[] = $val;
}
}
return $ret;
}
print_r(StartSearch("th", $str));
?>

PHP - isolate first letter from a text

I have a set of articles, in which I want to style the first letter from each article (with CSS).
the articles usually start with a paragrah, like:
<p> bla bla </p>
So how could I wrap the first letter from this text within a <span> tag ?
Unless you need to do something extremely fancy, there's also the :first-letter CSS selector.
<?php
$str = '<p> bla bla </p>';
$search = '_^<p> *([\w])(.+) *</p>$_i';
$replacement = '<p><span>$1</span>$2</p>';
$new = preg_replace( $search, $replacement, $str );
echo $new."\n";
You can do this in all CSS.
CSS supports "Pseudo-Elements" where you can choose the first letter / first word and format it differently from the rest of the document.
http://www.w3schools.com/CSS/CSS_pseudo_elements.asp
There's a compatibility chart; some of these may not work in IE 6
http://kimblim.dk/css-tests/selectors/
you could add a Php span but might not be as clean
$s = " la la ";
$strip = trim(strip_tags($s));
$t = explode(' ', $strip);
$first = $t[0];
// then replace first character with span around it
$replace = preg_replace('/^?/', '$1', $first);
// then replace the first time of that word in the string
$s = preg_replace('/'.$first.'/', $replace, $s, 1);
echo $s;
//not tested
I've not found a versatile method yet, but a traditional code implementation (that may be slower) works:
function pos_first_letter($haystack) {
$ret = false;
if (!empty($haystack)) {
$l = strlen($haystack);
$t = false;
for ($i=0; $i < $l; $i++) {
if (!$t && ($haystack[$i] == '<') ) $t = true;
elseif ($t && ($haystack[$i] == '>')) $t = false;
elseif (!$t && !ctype_space($haystack[$i])) {
$ret = $i;
break;
}
}
}
return $ret;
}
Then call:
$i = pos_first_letter( $your_string );
if ($i !== false) {
$output = substr($s, 0, $i);
$output .= '<span>' . substr($s, $i, 1) . '</span>';
$output .= substr($s, $i+1);
}

Php substr entire words

How can i substr 20 chars from $xbio and get only complete words?
$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'...';
TY
Found this searching stackoverflow - tell me what do you think please:
<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>
This is the function i always use:
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}
preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches);
echo $matches[1];
This is a function that i use for this kind of task:
function truncate($str, $maxLength, $append = '...') {
if (strlen($str) > $maxLength) {
$str = substr($str, 0, $maxLength);
$str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
$str = trim($str);
$str .= $append:
}
return $str;
}

Categories