php: Delete specific index from string? - php

I want to be able to specify an index in a string and remove it.
I have the following:
"Hello World!!"
I want to remove the 4th index (o in Hello). Here would be the end result:
"Hell World!!"
I've tried unset(), but that hasn't worked. I've Googled how to do this and that's what everyone says, but it hasn't worked for me. Maybe I wasn't using it right, idk.

This is a generic way to solve it:
$str = "Hello world";
$i = 4;
echo substr_replace($str, '', $i, 1);
Basically, replace the part of the string before from the index onwards with the part of the string that's adjacent.
See also: substr_replace()
Or, simply:
substr($str, 0, $i) . substr($str, $i + 1)

$str="Hello World";
$str1 = substr($str,0,4);
$str2 = substr($str,5,7);
echo $str1.$str2;

This php specific of working with strings also bugged me for a while. Of course natural solution is to use string functions or use arrays but this is slower than directly working with string index in my opinion. With the following snippet issue is that in memory string is only replaced with empty � and if you have comparison or something else this is not good option. Maybe in future version we will get built in function to remove string indexes directly who knows.
$string = 'abcdefg';
$string[3] = '';
var_dump($string);
echo $string;

$myVar = "Hello World!!";
$myArray = str_split($myVar);
array_splice($myArray, 4, 1);
$myVar = implode("", $myArray);
Personal I like dealing with arrays.
(Sorry about lack of code brackets putting this up via my phone)

I think can create a function and call it like this
function rem_inx ($str, $ind)
{
return substr($str,0,$ind++). substr($str,$ind);
}
//use
echo rem_inx ("Hello World!!", 4);

Related

Adding something to the start of a variable?

I am looking for some code that allows you to add +44 onto the beginning of my $string variable.
So the ending product would be:
$string = 071111111111
+44071111111111
Your $string variable isn't actually a string in this scenario; it's an integer. Make it a string by putting quotes around it:
$string = "071111111111"
Then you can use the . operator to append one string to another, so you could do this:
$string = "+44" . $string
Now $string is +44071111111111. You can read more about how to use the . (string concatenation operator) on the PHP documentation here.
Other people's suggestions of just keeping $string as an integer wouldn't work: "+44" . 071111111111 is actually +447669584457. Due to the 0 at the start of the number, PHP converts it to an octal number rather than a decimal one.
You can combine strings by .
$string = '+44'.$string;
You can use universal code, which works with another parameters too.
<?php
$code = "+44";
$string = "071111111111";
function prepend(& $string, $code) {
$test = substr_replace($string, $code, 0, 0);
echo $test;
}
prepend($string, $code);
?>

PHP read everything until first comma

I have string that will look like this:
$string = "hello, my, name, is, az";
Now I just wanna echo whatever is there before first comma. I have been using following:
echo strstr($this->tags, ',', true);
and It has been working great, but the problem it only works php 5.3.0 and above. I am currently on PHP 5.2.
I know this could be achieve through regular express by pregmatch but I suck at RE.
Can someone help me with this.
Regards,
<?php
$string = "hello, my, name, is, az";
echo substr($string, 0, strpos($string, ','));
You can (and should) add further checks to avoid substr if there's no , in the string.
Use explode than,
$arr = explode(',', $string,2);
echo $arr[0];
You can explode this string using comma and read first argument of array like this
$string = "hello, my, name, is, az";
$str = explode(",", $string, 2);
echo $str[0];
$parts = explode(',',$string);
echo $parts[0];
You can simple use the explode function:
$string = "hello, my, name, is, az";
$output = explode(",", $string);
echo $output[0];
Too much explosives for a small work.
$str = current(explode(',', $string));

Remove token variables

I'm in the process of writing a theme based script and need a way to replace "variables" or tokens that weren't replaced by the script.
The format is:
^_variablename_^
So say, after processing the following, with variables: name=Adam, Occupation=programmer
Hello, my name is ^_title_^^_name_^, and I work as a ^_occupation_^.
We'd be left with ^_title_^ still in place.
I need a way to get rid of these, without knowing the name of the "variable".
Thanks in advance :)
Process again:
$str = 'Hello, my name is ^_title_^Adam, and I work as a programmer.';
$str = preg_replace('/\^_(\w+)_\^/', '', $str);
echo $str;
Codepad
$str = 'Hello, my name is ^_title_^Adam, and I work as a programmer.';
echo preg_replace('/^_[\w_-]+_^/i', '', $str);
Try using preg_replace_callback, when substitute variables in so you can simply ignore ones you can't substitute in:
$input = 'Hello, my name is ^_title_^^_name_^, and I work as a ^_occupation_^. ';
$variables = array('name' => 'adam');
$re = preg_replace_callback('/\^_(?<var>.+?)_\^/', function($params) use ($variables) {
if (isset($variables[$params['var']])) {
return $variables[$params['var']];
} else {
return '';
}
},
$input);
print $re;
This uses anonymous function syntax that works since php 5.3.0, you might need to declare a separate callback for this if you want to use it on earlier versions.

Shortcut for: $foo = explode(" ", "bla ble bli"); echo $foo[0]

is there a way to get the n-th element of a splitted string without using a variable?
My PHP code always looks like this:
$foo = explode(" ", "bla ble bli");
echo $foo[0];
Is there a shorter way maybe like in Python?
print "bla ble bli".split(" ")[0]
Thanks in advance.
This is what people should be using instead of explode most of the time:
$foo = strtok("bla ble bli", " ");
It cuts off the first string part until the first " ".
If you can't let go of explode, then the closest idiom to accomplish [0] like in Python is:
$foo = current(explode(...));
If it's not just the first element, then it becomes a tad more cumbersome:
$foo = current(array_slice(explode(...), 2)); // element [2]
(Not really an answer per se -- others did answer pretty well)
This is one of the features that should arrive with one of the next versions of PHP (PHP 5.4, maybe).
For more informations, see Features in PHP trunk: Array dereferencing -- quoting one of the given examples :
<?php
function foo() {
return array(1, 2, 3);
}
echo foo()[2]; // prints 3
?>
try this:
its one line:
<?php
echo (($f=explode(" ", "bla ble bli"))?$f[0]:'');
?>
result here:
http://codepad.org/tnhbpYdd
Why not just do:
function splode($string, $delimiter, $index){
$r = explode($delimiter, $string);
return $r[$index];
}
I use like a hojillion little functions like this.
With only one expression I can think of:
echo list($a) = explode(' ', 'a b c') ? $a : '';
echo list($_, $b) = explode(' ', 'a b c') ? $b : '';
Not as far as I know although you could define a function and use that.
function firstWord($string) {
$foo = explode(" ", $string);
return $string;
}
I don't know of a way to do what you want, even though I've wanted to do the same thing many times before. For that specific case you could do
$bar = substr($foo, 0, strpos($foo, " "));
which stops there being one extra variable, but isn't exactly what you wanted.
The following is probably the cleanest way I can think of doing what OP has requested. It defines a function, but no variables of it's own and it'll get the job done for just about any situation:
function at(&$arr, &$pos) { return $arr[$pos]; }
Example usage:
echo at( explode('|', 'a|b|c|d'), 1 ); // Outputs 'b'
The function is a single line of code and wouldn't be hard to commit to memory. If you're only using it once, you can define it in the local scope of where it'll be used to minimize code clutter.
As a slight added benefit, because the function does no checks on $arr or $pos, it'll throw all the same errors that it would if you tried to access a non-existent index for an array, or will even return the individual characters in a string or items in a key-value paired array.
close. the right track is making a function or method for something that gets repeated.
function extract_word($input, $index) {
$input = explode(' ', $input);
return $input[$index];
}
add a third argument of $separater = ' ' if you may have different word separaters.

How can we split a sentence

I have written the PHP code for getting some part of a given dynamic sentence, e.g. "this is a test sentence":
substr($sentence,0,12);
I get the output:
this is a te
But i need it stop as a full word instead of splitting a word:
this is a
How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?
use wordwrap
If you're using PHP4, you can simply use split:
$resultArray = split($sentence, " ");
Every element of the array will be one word. Be careful with punctuation though.
explode would be the recommended method in PHP5:
$resultArray = explode(" ", $sentence);
first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.
Try using explode() function.
In your case:
$expl = explode(" ",$sentence);
You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:
$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
print $expl[$i]." ";
}
Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.
function niceTrim($str, $trimLen) {
$strLen = strlen($str);
if ($strLen > $trimLen) {
$trimStr = substr($str, 0, $trimLen);
return substr($trimStr, 0, strrpos($trimStr, ' '));
}
return $str;
}
$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);
This will print
this is a
as required.
Hope this is the solution you are looking for!
this is just psudo code not php,
char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}
new_constructed_sentence is what you want!!!

Categories