In PHP, how can you replace the second and third character of a string with an X so string would become sXXing?
The string's length would be fixed at six characters.
Thanks
It depends on what you are doing.
In most cases, you will use :
$string = "string";
$string[1] = "X";
$string[2] = "X";
This will sets $string to "sXXing", as well as
substr_replace('string', 'XX', 1, 2);
But if you want a prefect way to do such a cut, you should be aware of encodings.
If your $string is 我很喜欢重庆, your output will be "�XX很喜欢" instead of "我XX欢重庆".
A "perfect" way to avoid encoding problems is to use the PHP MultiByte String extension.
And a custom mb_substr_replace because it has not been already implemented :
function mb_substr_replace($output, $replace, $posOpen, $posClose) {
return mb_substr($output, 0, $posOpen) . $replace . mb_substr($output, $posClose + 1);
}
Then, code :
echo mb_substr_replace('我很喜欢重庆', 'XX', 1, 2);
will show you 我XX欢重庆.
Simple:
<?php
$str = "string";
$str[1] = $str[2] = "X";
echo $str;
?>
For replacing, use function
$str = 'bar';
$str[1] = 'A';
echo $str; // prints bAr
or you could use the library function substr_replace as:
$str = substr_replace($str,$char,$pos,1);
similarly for 3rd position
function mb_substr_replace($string, $replacement, $start, $length=0)
{
return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start+$length);
}
same as above, but standardized to be more like substr_replace (-substr- functions usually take length, not end position)
Related
How to remove 4th letter in string using PHP ?
I use this code.
<?php
$str = "1234567890";
$str2 = mb_substr($str, 4);
echo $str2;
?>
But it's will echo 567890
I want to echo 123567890 remove 4 from string.
How can i do ?
You can try substr_replace for this. Here we are replacing 4 which is at 3rd index.
Try this code snippet here
<?php
$str = "1234567890";
echo substr_replace($str, "", 3,1);
try setting the 3rd index to null
<?php
$str = "1234567890";
$str[3] = null;
echo $str;
try with below sulution:
$str = '1234567890';
$str_arr = str_split($str);
unset($str_arr[3]);
echo implode('', $str_arr);
output:
123567890
There are multiple ways of performing any operations on string variables in php
// can be used for printing purpose
$str = "1234567890";
echo substr($str,0,3).substr($str,4);
// actual replacement of string
$str = "1234567890";
echo substr_replace($str, "", 3,1);
i have one string
$str ='california 94063';
now i want california and 94063 both in diferent variable.
string can be anything
Thanks in advance....
How about
$strings = explode(' ', $str);
Assuming that your string has ' ' as a separator.
Then, if you want to find the numeric entries of the $strings array, you can use is_numeric function.
Do like this
list($str1,$str2)=explode(' ',$str);
echo $str2;
If your string layout is always the same (say: follows a given format) then I'd use sscanf (http://www.php.net/manual/en/function.sscanf.php).
list($str, $number) = sscanf('california 94063, "%str %d");
<?php
$str ='california 94063';
$x = preg_match('(([a-zA-Z]*) ([0-9]*))',$str, $r);
echo 'String Part='. $r[1];
echo "<br />";
echo 'Number Part='.$r[2];
?>
If text pattern can be changed then I found this solution
Source ::
How to separate letters and digits from a string in php
<?php
$string="94063 california";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
if(isNumber($string[$index]))
$nums .= $string[$index];
else
$chars .= $string[$index];
}
echo "Chars: -".trim($chars)."-<br>Nums: -".trim($nums)."-";
function isNumber($c) {
return preg_match('/[0-9]/', $c);
}
?>
php noob here trying to create a function but can't quite find the resource on the web that rids my confusions. Here it goes;
I want to create a function which takes a variable name, for example
Thief's Wit (4)
And converts it to
thiefswit.jpg
So far, here is what I have
THIS CODE IS LOADED TO TEST MY FUNCTION
require_once 'functions.php';
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
?>
THIS CODE IS THE ACTUAL FUNCTION
function convertImage($string)
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
substr ($string, 0, ($stringlength-4));
$string = strtolower ($string);
$string = "$string" . ".jpg";
return $string;
}
?>
The format of the strings will always be
NAME HERE (4)
which is why I substr the length-4.
When I run this function, it echoes the original string.
Any help here?
I'm new to PHP and don't really understand
a) What the 'return' does at the end of the function and
b) Does the function inherently know to replace "$string" with the variable you tell it to act on in another file? In this case $mod.
Thanks!
You need to save the output of the function:
$mod = "Thief's Wit (4)";
$mod = convertImage($mod); // save the return value to $mod variable
echo $mod;
The return value of a function is the value you get from calling a function. So convertImage($mod) will have the value that you return. At this point, you need to store the results to a variable, which you can do by doing $mod = convertImage($mod);
An alternative would be to "pass by reference", where modifying the arguments of your function will modify the variables themselves.
function convertImage(&$string) // use &$string to pass by reference
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
substr ($string, 0, ($stringlength-4));
$string = strtolower ($string);
$string = "$string" . ".jpg";
//return $string; this won't be needed anymore
}
...
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
You have to either return the new string you created
$mod = convertImage($mod);
Or pass by reference, which means that the function convertImage is working with the same reference to the passed in string as its caller
function convertImage(&$string) {...}
convertImage($mod); // $mod will point to a new string after the call
function convertImage(&$string) {
$string = strtolower(preg_replace("/[^a-zA-Z]+/", "", $string));
}
should do all you need - it will strip any punctuation and numbers etc, and make it lower case.
edited to allow passing by reference
You aren't assigning the variable value anywhere. To get the actual result, you'd have the function return value to a variable, like so:
$mod = convertImage($mod);
Once the actual function output is stored in a variable, you'll be able to use it anywhere as you like.
Demo: http://codepad.org/naFB74K6
<?php
function convertImage(&$string)
{
$string = preg_replace('/\s+/', '', $string); //Thief'sWit(4)
$string = str_replace("'", "", $string); //ThiefsWit(4)
$string = substr($string, 0, strlen($string)-3); //ThiefsWit
$string = strtolower($string); //thiefswit
return $string.".jpg";
}
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
?>
I have a problem with a PHP breadcrumb function I am using, when the page name is very long, it overflows out of the box, which then looks really ugly.
My question is, how can I achieve this: "This is a very long string" to "This is..." with PHP?
Any other ideas on how I could handle this problem would also be appreciated, thanx in advance!
Here is the breadcrumb function:
function breadcrumbs() {
// Breadcrumb navigation
if (is_page() && !is_front_page() || is_single() || is_category()) {
echo '<ul class="breadcrumbs">';
echo '<li class="front_page">'.get_bloginfo('name').' <span style="color: #FFF;">»</span> </li>';
if (is_page()) {
$ancestors = get_post_ancestors($post);
if ($ancestors) {
$ancestors = array_reverse($ancestors);
foreach ($ancestors as $crumb) {
echo '<li>'.get_the_title($crumb).' <span style="color: #FFF;">»</span> </li>';
}
}
}
if (is_single()) {
$category = get_the_category();
echo '<li>'.$category[0]->cat_name.'</li>';
}
if (is_category()) {
$category = get_the_category();
echo '<li>'.$category[0]->cat_name.'</li>';
}
// Current page
if (is_page() || is_single()) {
echo '<li class="current">'.get_the_title().'</li>';
}
echo '</ul>';
} elseif (is_front_page()) {
// Front page
echo '<ul class="breadcrumbs">';
echo '<li class="front_page">'.get_bloginfo('name').'</li>';
echo '<li class="current">Home Page</li>';
echo '</ul>';
}
}
If you want a more nice (word limited) trucation you can use explode to split the string by spaces and then append each word (array entry) until you've reached your max limit
Something like:
define("MAX_LEN", 15);
$sentance = "Hello this is a long sentance";
$words = explode(' ', $sentance);
$newStr = "";
foreach($words as $word) {
if(strlen($newStr." ".$word) >= MAX_LEN) {
break;
}
$newStr = $newStr." ".$word;
}
If you are working with UTF-8 as charset, I suggest using the mb_strimwidth method as it is multibyte safe and won´t mess up multibyte chars. It also appends a placeholder string like ... automatically, with substr you´d have to do that in an additional step.
Usage sample:
echo mb_strimwidth("Hello World", 0, 10, "...", "UTF-8"); // .. or some other charset
// outputs Hello W...
You can safely use substr.
and eventually wordwrap() to break long words
$string = "This is a very long string";
$newString = substr( $string, 0, 7)."...";
// Output = This is...
Ideally, it should be done on the client side. You can use CSS/JS for the same.
Set this CSS property: text-overflow: ellipsis.
However, it will work only in IE. To use the same in Firefox as well, you can do something like this.
If you do not mind javascript plugins, use one of the jQuery ellipsis plugin.
Edit: These methods will work even when dealing with unicode, which can be a bit tricky if you try to handle this using php. (Like substr function)
Edit 2: If your problem is just the overflowing text and you do not mind not having the "..." at the end then it is even more simple. Simply, use the CSS: text-overflow: hidden;.
You can truncate the string at max length and then search for the last space:
Multibyte safe (Requires PHP > = 4.2)
function mb_TruncateString($string, $length = 40, $marker = "...")
{
if (mb_strlen($string) <= $length)
return $string;
// Trim at given length
$string = mb_substr($string, 0, $length);
// Get the text before the last space
if(mb_ereg("(.*)\s", $string, $matches))
$string = $matches[1];
return $string . $marker;
}
Following is not multibyte safe
function TruncateString($string, $length = 40, $marker = "...")
{
if (strlen($string) <= $length)
return $string;
// Trim at given length
$string = substr($string, 0, $length);
// Get the text before the last space
if(preg_match("/(.*)\s/i", $string, $matches))
$string = $matches[1];
return $string . $marker;
}
You're after a truncate function. This is what I use:
/**
* #param string $str
* #param int $length
* #return string
*/
function truncate($str, $length=100)
{
$str = substr($str, $length);
$words = explode(' ', $str); // separate words into an array
array_pop($words); // discard last item, as 9/10 times it's a partial word
$str = implode(' ', $words); // re-glue the string
return $str;
}
And usage:
echo truncate('This is a very long page name that will eventually be truncated', 15);
I have the following string in a variable.
Stack Overflow is as frictionless and painless to use as we could make it.
I want to fetch first 28 characters from the above line, so normally if I use substr then it will give me Stack Overflow is as frictio this output but I want output as:
Stack Overflow is as...
Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP?
Edited:
I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.
You can use the wordwrap() function, then explode on newline and take the first part:
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
From AlfaSky:
function addEllipsis($string, $length, $end='…')
{
if (strlen($string) > $length)
{
$length -= strlen($end);
$string = substr($string, 0, $length);
$string .= $end;
}
return $string;
}
An alternate, more featureful implementation from Elliott Brueggeman's blog:
/**
* trims text to a space then adds ellipses if desired
* #param string $input text to trim
* #param int $length in characters to trim to
* #param bool $ellipses if ellipses (...) are to be added
* #param bool $strip_html if html tags are to be stripped
* #return string
*/
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
$trimmed_text = substr($input, 0, $last_space);
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
(Google search: "php trim ellipses")
Here's one way you could do it:
$str = "Stack Overflow is as frictionless and painless to use as we could make it.";
$strMax = 28;
$strTrim = ((strlen($str) < $strMax-3) ? $str : substr($str, 0, $strMax-3)."...");
//or this way to trim to full words
$strFull = ((strlen($str) < $strMax-3) ? $str : strrpos(substr($str, 0, $strMax-3),' ')."...");
This is the easiest way:
<?php
$title = "this is the title of my website!";
$number_of_characters = 15;
echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " "));
?>
This is the simplest solution I know of...
substr($string,0,strrpos(substr($string,0,28),' ')).'...';
I would use a string tokenizer to split the string into words much like this:
$string = "Stack Overflow is as frictionless and painless to use as we could make it.";
$tokenized_string = strtok($string, " ");
Then you can pull out the individual words any way you want.
Edit: Greg has a much better and more elegant way of doing what you want. I would go with his wordwrap() solution.
you can use wordwrap.
string wordwrap ( string $str [, int $width= 75 [, string $break= "\n" [, bool $cut= false ]]] )
-
function firstNChars($str, $n) {
return array_shift(explode("\n", wordwrap($str, $n)));
}
echo firstNChars("bla blah long string", 25) . "...";
disclaimer: didn't test it.
additionally, if your string contains \ns, it might get broken earlier.
try:
$string='Stack Overflow is as frictionless and painless to use as we could make it.';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');
$string='Stack Overflow';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');
function truncate( $string, $limit, $break=" ", $pad="...") {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit){
return $string;
}
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strrpos($string, $break))){
$string = substr($string, 0, $breakpoint);
}
return $string . $pad;
}
Problems can arise if your string has html tags,   and multiple spaces. Here is what I use that takes care of everything:
function LimitText($string,$limit,$remove_html=0){
if ($remove_html==1){$string=strip_tags($string);}
$newstring = preg_replace("/(?:\s| )+/"," ",$string, -1); // replace   with space
$newstring = preg_replace(array('/\s{2,}/','/[\t\n]/'),' ',$newstring); // replace duplicate spaces
if (strlen($newstring)<=$limit) { return $newstring; } // ensure length is more than $limit
$newstring = substr($newstring,0,strrpos(substr($newstring,0,$limit),' '));
return $newstring;
}
usage:
$string = 'My wife is jealous of stackoverflow';
echo LimitText($string,20);
// My wife is jealous
usage with html:
$string = '<div><p>My wife is jealous of stackoverflow</p></div>';
echo LimitText($string,20,1);
// My wife is jealous
This's Working for me Perfect
function WordLimt($Keyword,$WordLimit){
if (strlen($Keyword)<=$WordLimit) { return $Keyword; }
$Keyword= substr($Keyword,0,strrpos(substr($Keyword,0,$WordLimit),' '));
return $Keyword;
}
echo WordLimt($MyWords,28);
// OutPut : Stack Overflow is as
it will adjust and break on last Space without cut word...
why not try exploding it and getting the first 4 elements of the array?
substr("some string", 0, x);
From the PHP Manual