Blog

Most Popular PHP String Functions
Posted on March 21, 2018 in PHP by Matt Jennings

substr()

// Example string
$blog = 'Your blog is Excellent!';

// returns 'our blog is Excellent!'
substr($blog, 1);

// returns 'xcellent!'
substr($blog, -9);

// returns 'Your'
substr($blog, 0, 4);

// returns 'Blog'
substr($blog, 5, -13);

strlen()

// 13
echo strlen('Super Friends');

trim()

$string = ' blah my string blah ';

// 'blah my string blah'
echo trim($string);

$trimmed = trim(trim($string), 'blah');
// 'my string'
echo $trimmed;

strpos()

$string = 'Super Friends';

// 12
echo strpos($string, 's');

strtoupper()

$string = 'loud';

// 'LOUD'
echo strtoupper($string);

strtolower()

$string = 'QUIET';

// 'LOUD'
echo strtolower($string);

is_string()

// 'false'
if( is_string(7) )
{
  echo 'true';
}
else
{
  echo 'false';
}

strstr()

$email = '';

// 'mattjennings.net'
echo substr(strstr($email, '@'), 1);

// 'matt'
echo strstr($email, '@', true);

// '@mattjennings.net'
echo strstr($email, '@', false);

$url = 'mattjennings.net';

if( strstr($url, 'https://www.') === false )
{
  $url = 'https://www.' . $url;
}
// 'https://www.mattjennings.net'
echo $url;

str_replace()

$string = 'Silence is golden.';

$search = 'golden';

$replace = 'outlawed';

// 'Silence is outlawed.'
echo str_replace($search, $replace, $string);

ucfirst()

$string = 'my string';

// 'My string'
echo ucfirst($string);

ucwords()

$string = 'my string';

// 'My String'
echo ucwords($string);

Leave a Reply