Remove token variables - php

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.

Related

php How to add comma's in an array without making it separate values?

My string:
'KCP-PRO;first_name last_name;address;zipcode;country' //for example: 'KCP-PRO;Jon Doe;Box 564;02201;USA'
or
'KCP-SAT-PRO;first_name last_name;address;zipcode;country'
How can i change the first part (KCP-PRO or KCP-SAT-PRO) and change it to (KCP,PRO or KCP,SAT,PRO)? The outcome has to be:
'KCP,PRO;first_name last_name;address;zipcode;country'
or
'KCP,SAT,PRO;first_name last_name;address;zipcode;country'
I haven't tried the code myself but I guess this will do the trick
$string = 'KCP-SAT-PRO;first_name last_name;address;zipcode;country';
$stringExploded = explode(';', $string);
$stringExploded[0] = str_replace('-', ',', $stringExploded[0]);
$output = implode(';', $stringExploded);
//output should be KCP,SAT,PRO;first_name last_name;address;zipcode;country
Hope this helps :)
Or you can use preg_replace_callback function with the following regex
^[^;]*
So your code looks like as
echo preg_replace_callback("/^[^;]*/",function($m){
return str_replace("-",',',$m[0]);
},"KCP-SAT-PRO;first_name last_name;address;zipcode;country");

PHP match and replace whole word

Hi I am replacing certain names with different value . Here is values I am replacing "#size-name" and "#size" .But the problem is my code replacing only size first and note name for example
#size = "replaceword"
#size-name = "replaceword2"
But its replacing
#size ="replaceword"
#size-name = "replaceword2-name"
How can I replace whole word not part of it here is my code
$tempOutQuery = preg_replace("/(\b($key)\b)/i" , $value , $tempOutQuery);
$tempOutQuery= str_replace("#".$key ,$value ,$tempOutQuery);
both codes are not working
My Full Code
$val= "Hi I want #size dress which is #size-name";
$tempOutQuery = preg_replace("/(\b(size)\b)/i" ,"replaceword", $tempOutQuery);
$tempOutQuery = preg_replace("/(\b(size-name)\b)/i" ,"replaceword2", $tempOutQuery);
If you could make replace without using regulat expressions, then I would suggest using standart str_replace() with arrays:
$val= "Hi i want #size dress which is #size-name";
$search = array('size-name', 'size');
$replace = array('replaceword2', 'replaceword');
$result = str_replace($search, $replace, $val);
The order of search and replace Strings is important!
You should take care that you replace long search-strings first, and the short strings later.
Here's another option for you, using preg_replace_callback. It's actually very similar to Gennadiy's method. The only real difference is that it's using the preg aspect of PHP (and it's a lot more work). But it's another way to skin the proverbial cat.
<?php
// SET OUR DEFAULT STRING
$string = 'Hi I want #size suit which is #size-name';
// LOOK FOR EITHER size-name OR size AND IF YOU FIND IT ...
// RUN THE FUNCTION 'replace_sizes'
$string = preg_replace_callback('~#(size-name|size)~', 'replace_sizes', $string);
// PRINT OUT OUR MODIFIED STRING
print $string;
// THIS IS THE FUNCTION THAT WILL BE RUN EVERY TIME A MATCH IS FOUND
// EITHER 'size' OR 'size-name' WILL BE STORED IN $m[1]
function replace_sizes($m) {
// SET UP AN ARRAY THAT HAS OUR POTENTIAL MATCHES AS KEYS
// AND THE TEXT WE WANT TO REPLACE WITH AS THE VALUE
$size_text_array = array('size-name' => 'replaceword2', 'size' => 'replaceword');
// RETURN WHATEVER THE VALUE IS BASED ON THE KEY
return $size_text_array[$m[1]];
}
This will print out:
Hi I want replaceword suit which is replaceword2
Here is a working demo:
http://ideone.com/njNTbB
You can try pre_replace() to replace whole word from an item of an array in PHP a shown below.
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\band\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
See the entire post here

php: Delete specific index from string?

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);

Function to shorten a specific string

I have this string:
$str="http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
Is there a built-in php function that can shorten it by removing the ._SL110_.jpg part, so that the result will be:
http://ecx.images-amazon.com/images/I/418lsVTc0aL
no, there's not any built in URL shortener php function, if you want to do something similar you can use the substring or create a function that generates a short link and stores the long and short value somewhere in database and display only the short one.
well, it depends if you need a regexp replace (if you don't know the complete value) or if you can do a simple str_replace like below:
$str = str_replace(".SL110.jpg", "", "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg");
You can use preg_replace().
For example preg_replace("/\.[^\.]+\.jpg$/i", "", $str);
I would recommend using:
$tmp = explode("._", $str);
and then using $tmp[0] for your purpose, if you make sure the part you want to get rid of is always separated by "._" (dot-underscore) symbols.
You can try
$str = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
echo "<pre>";
A.
echo strrev(explode(".", strrev($str), 3)[2]) , PHP_EOL;
B.
echo pathinfo($str,PATHINFO_DIRNAME) . PATH_SEPARATOR . strstr(pathinfo($str,PATHINFO_FILENAME),".",true), PHP_EOL;
C.
echo preg_replace(sprintf("/.[^.]+\.%s$/i", pathinfo($str, PATHINFO_EXTENSION)), null, $str), PHP_EOL;
Output
http://ecx.images-amazon.com/images/I/418lsVTc0aL
See Demo
you could do this substr($data,0,strpos($data,"._")), if what you want is to strip everything after "._"
No, it is not (at least not directly). Such URL shorteners usually generate unique ID and remember your original URL and generated ID. When you enter such url, you start a script, which looks for given ID and then redirect to target URL.
If you want just cut of some portion of your string, then assuming that filename format is as you shown, just look for 1st dot and substr() to that place. Or
$tmp = explode('.', $filename);
$shortName = $tmp[0];
If suffix ._SL110_.jpg is always there, then simply str_replace('._SL110_.jpg', '', $filename) could work.
EDIT
Above was example for filename only. Whole code would be:
$url = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
$urlTmp = explode('/', $url);
$fileNameTmp = explode( '.', $urlTmp[ count($urlTmp)-1 ] );
$urlTmp[ count($urlTmp)-1 ] = $fileNameTmp[0];
$newUrl = implode('/', $urlTmp );
printf("Old: %s\nNew: %s\n", $url, $newUrl);
gives:
Old: http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg
New: http://ecx.images-amazon.com/images/I/418lsVTc0aL

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.

Categories