String function (str_replace) in php - php

I have a PHP function as follows:
<?php
function fixEncoding ($str){
$searchVal = array("?", "=", ":", ";", "#", "+", "%", "&" );
$replaceVal = array("%3F", "%3D", "%3A", "%3B", "%23", "%2B", "%25", "%26" );
return str_replace($searchVal, $replaceVal, $str);
}
$test_string = "www.joensuu.fi/documents/144181/2569169/Joensuun-Areena.jpg/69933c17-e619-7d05-a64a-94bfbb533da9?t=1550323540726";
$result = fixEncoding($test_string);
echo $result;
?>
Output:
www.joensuu.fi/documents/144181/2569169/Joensuun-Areena.jpg/69933c17-e619-7d05-a64a-94bfbb533da9%253Ft%253D1550323540726
This function successfully replaces '?' and '=' characters, however, it later replaces their '%' character with '%25' also, which does not make it expected output.
Any suggestions, for how I can handle this.

put % first in your array like
$searchVal = array("%", "?", "=", ":", ";", "#", "+", "&" );
but you should also consider using JureW's answer

If I uderstand you correctly, you want something like this:
www.joensuu.fi%2Fdocuments%2F144181%2F2569169%2FJoensuun-Areena.jpg%2F69933c17-e619-7d05-a64a-94bfbb533da9%3Ft%3D1550323540726
If so, no need to build your own function:
print_r(urlencode($test_string)); // outputs same as example above
PHP has built in function for encoding/decoding url's, so lets not reinvent the wheel and use those :)

try this:
function fixEncoding ($str){
return urlencode($str);
}
$test_string = "test???";
$result = fixEncoding($test_string);
echo $result;

Related

Add hyperlinks to words in php

I have found this function on buildinternet.com.
function tag_it($text) {
$text = preg_replace("/:(\w+):/", '$1',$text);
return $text;
}
What it does is adding hyperlinks to words enclosed in ":" and the problem is that it works only with single words and it doesn`t work with words that has a single quote.
So if I do this,
$test = "one :word1:, :two words:, :this is a phrase:, this has a single quote :don't: or :don't forget:.";
echo tag_it($test);
only to the :word1: will be added a hyperlink, the rest will be ignored.
I don`t know too much php and I would appreciate if someone could make the function work with more than one word and with a single quote too.
Thank you!
Edit:
So I have tried the following to add a different link to words enclosed in "#"
function tag_it($text) {
$out = preg_replace_callback(
"/:([^\:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},
preg_replace_callback(
"/#([^\#]+)#/",
function($m1) {
$linkText1 = $m1[1];
$link1 = str_replace('"', '', $m1[1]);
$link1 = str_replace("'", "", $m1[1]);
$link1 = str_replace(" ", "_", $link1);
return ''.$linkText1.'';
},
$text
)
);
return $out;
}
$test = "one :word:, #two words#, :this is a phrase:, this has a single quote :don:'t or :don't forget:.";
echo tag_it($test);
and i get this
one word, two_words,_/" title="//www.example.com/blog/two_words/" title="two words" target="_blank">two words, " target="_blank">//www.example.com/blog/two_words/" title="two words" target="_blank">two words, this is a phrase, this has a single quote don't or don't forget:.
It seems to work for the 1st word enclosed in ":" and is trying to work with the words enclosed in "#" too but something is happening along the way and I can`t figure it out.
Any tip is really appreciated.
Thank you!
Change the crucial line in the function to the following:
$text = preg_replace("/:([^:]+):/", '$1', $text);
change this /:(\w+):/ to this /:([^:]+):/
Try this hope this simple one will help you out..
Regex: :([^\:]+):
:([^\:]+): it will match : then all till not : and then : in end
Try this code snippet here
<?php
ini_set('display_errors', 1);
$test = "one :word1:, :two words:, :this is a phrase:, this has a single quote :don't: or :don't forget:.";
echo tag_it($test);
function tag_it($text)
{
$text = preg_replace("/:([^\:]+):/", '$1', $text);
return $text;
}
I'll let you finish it off, above are all valid, but leave you with broken links, so building on them, I'd do something like:
function tag_it($text) {
$out = preg_replace_callback(
"/:([^:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', "", $m[1]);
$link = str_replace("'", "", $m[1]);
return ''.$linkText.'';
},
$text);
return $out;
}
You'll need to finish it off to replace spaces with - or _ or something but should be easy enough to work it out.
To answer to my "Edit:", I have figured out the problem.
Here is the full function
function tag_it($text) {
$out = preg_replace_callback(
"/:([^\:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$text
);
$out = preg_replace_callback(
"/#([^\#]+)#/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$out
);
$out = preg_replace_callback(
"/#([^\#]+)#/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$out
);
return $out;
}
$test = "one :word:, #two words#, #this is a phrase#, this has a single quote #don't# or :don't forget:.";
echo tag_it($test);

how do you parse out a text value in php

I have a line like this:
$line1= "System configuration: lcpu=96 mem=393216MB ent=16.00"
I need to parse out lcpu, mem and ent values from this string. I have tried something like this:
$lcpu=preg_match('/(?P<lcpu>\w+)= (?P<digit>\d+)/', $line1, $matches);
does not seem to be getting the lcpu values from the string $line1, any ideas what I am doing wrong here?
You've nearly got a query string there, so maybe
$string = explode(": ", $line1);
$string = str_replace(" ", "&", $string[1]);
parse_str($string, $values);
echo $values['lcpu'];
One other way to pares strings:
$line1= "System configuration: lcpu=96 mem=393216MB ent=16.00";
list($lcpu, $mem, $ent) = sscanf($line1, "System configuration: lcpu=%d mem=%dMB ent=%f");
Why not use a simple function to get the string between two strings. If the lcpu value is always going to be prefixed by "lcpu=" and end with a " " (space) then you could use:
function getBetween($str, $start, $end)
{
$r = explode($start, $str);
if (isset($r[1]))
{
$r = explode($end, $r[1]);
return $r[0];
}
return false;
}
and just say:
if (getBetween($line1, 'lcpu=', ' ')) { ... }
It'll return false if nothing is found.
Personally, I would parse by syntax instead (rather than searching for specific keys):
<?php
$input = "System configuration: lcpu=96 mem=393216MB ent=16.00";
// Strip out "System configuration: "
$values = preg_replace('~^.*?:\s*$~', '', $input);
// Split on whitespace separator
$values = preg_split('~\s+~', $values);
// Convert to associative array
foreach ($values as $i => $item)
{
// Explode on assignment (=)
list($k, $v) = explode('=', $item);
$values[$k] = $v;
unset($values[$i]);
}
There are many ways to parse a string. Explode is usually faster than using a regex, so this way may be more performant than the methods which rely on regular expressions.
list( , , $lcpu_pair )= explode( " ", $line1 );
list( , $lcpu_value ) = explode( "=", $lcpu_pair );
$lcpu_value will contain '96'.

Reversion Strings and replace a character - RegEx with Php

I have a doubt again on RegEx in Php.
Assume that I have a line like this
716/52 ; 250/491.1; 356/398; 382/144
I want the output to be
Replace all semi-colon with comma. I think I can do this using
$myline= str_replace(";", ",", $myline);
Interchange the numbers and replace '/' with a comma. That is, 716/52 will become 52,716. This is where I get stuck.
So, the output should be
52,716 , 491.1,250, 398,356, 144,382
I know that using sed, I can achieve it as
1,$s/^classcode:[\t ]\+\([0-9]\+\)\/\([0-9]\+\)/classcode: \2\,\1/
But, how do I do it using preg_match in php?
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', 'reverse', $str);
function reverse($matches)
{
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}
var_dump($res);
And working sample: http://ideone.com/BeS9j
UPD: PHP 5.3 version with anonymous functions
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = str_replace(';', ',', $str);
$res = preg_replace_callback('~[\d.]+/[\d.]+~', function ($matches) {
$parts = explode('/', $matches[0]);
return $parts[1] . ',' . $parts[0];
}, $str);
var_dump($res);
As an alternative to Regexen you could try this:
echo join(', ', array_map(
function ($s) { return join(',', array_reverse(explode('/', trim($s)))); },
explode(';', $string)));
$str = '716/52 ; 250/491.1; 356/398; 382/144';
$str = preg_replace('(\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)', '$2,$1', $str);
$str = str_replace(';', ',', $str);
Uses two capture groups, replacing them in reverse order. See it here.

PHP - a function to "sanitize" a string

is there any PHP function available that replaces spaces and underscores from a string with dashes?
Like:
Some Word
Some_Word
Some___Word
Some Word
Some ) # $ ^ Word
=> some-word
basically, the sanitized string should only contain a-z characters, numbers (0-9), and dashes (-).
This should produce the desired result:
$someword = strtolower(preg_replace("/[^a-z]+/i", "-", $theword));
<?php
function sanitize($s) {
// This RegEx removes any group of non-alphanumeric or dash
// character and replaces it/them with a dash
return strtolower(preg_replace('/[^a-z0-9-]+/i', '-', $s));
}
echo sanitize('Some Word') . "\n";
echo sanitize('Some_Word') . "\n";
echo sanitize('Some___Word') . "\n";
echo sanitize('Some Word') . "\n";
echo sanitize('Some ) # $ ^ Word') . "\n";
Output:
Some-Word
Some-Word
Some-Word
Some-Word
Some-Word
You might like to try preg_replace:
http://php.net/manual/en/function.preg-replace.php
Example from this page:
<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
//April1,2003
?>
You might like to try a search for "search friendly URLs with PHP" as there is quite a bit of documentation, example:
function friendlyURL($string){
$string = preg_replace("`\[.*\]`U","",$string);
$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');
$string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string );
$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);
return strtolower(trim($string, '-'));
}
and usage:
$myFriendlyURL = friendlyURL("Barca rejects FIFA statement on Olympics row");
echo $myFriendlyURL; // will echo barca-rejects-fifa-statement-on-olympics-row
Source: http://htmlblog.net/seo-friendly-url-in-php/
I found a few interesting solutions throughout the web.. note none of this is my code. Simply copied here in hopes of helping you build a custom function for your own app.
This has been copied from Chyrp. Should work well for your needs!
/**
* Function: sanitize
* Returns a sanitized string, typically for URLs.
*
* Parameters:
* $string - The string to sanitize.
* $force_lowercase - Force the string to lowercase?
* $anal - If set to *true*, will remove all non-alphanumeric characters.
*/
function sanitize($string, $force_lowercase = true, $anal = false) {
$strip = array("~", "`", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
"}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
"—", "–", ",", "<", ".", ">", "/", "?");
$clean = trim(str_replace($strip, "", strip_tags($string)));
$clean = preg_replace('/\s+/', "-", $clean);
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
EDIT:
Even easier function I found! Just a few lines of code, fairly self-explanitory.
function slug($z){
$z = strtolower($z);
$z = preg_replace('/[^a-z0-9 -]+/', '', $z);
$z = str_replace(' ', '-', $z);
return trim($z, '-');
}
Not sure why #Dagon chose to leave a comment instead of an answer, but here's an expansion of his answer.
php's preg_replace function allows you to replace anything with anything else.
Here's an example for your case:
$input = "a word 435 (*^(*& HaHa";
$dashesOnly = preg_replace("#[^-a-zA-Z0-9]+#", "-", $input);
print $dashesOnly; // prints a-word-435-HaHa;
You can think of writing this piece of code with the help of regular expressions.
But I dont see any available functions which help you directly replace the " " with "-"

Strip bad Windows filename characters

I found this function that tests whether a string is Windows filename and folder friendly:
function is_valid_filename($name) {
$parts=preg_split("/(\/|".preg_quote("\\").")/",$name);
if (preg_match("/[a-z]:/i",$parts[0])) {
unset($parts[0]);
}
foreach ($parts as $part) {
print "part = '$part'<br>";
if (preg_match("/[".preg_quote("^|?*<\":>","/")."\a\b\c\e\x\v\s]/",$part)||preg_match("/^(PRN|CON|AUX|CLOCK$|NUL|COMd|LPTd)$/im",str_replace(".","\n",$part))) {
return false;
}
}
return true;
}
What I'd rather have is a function that strips all the bad stuff from the string. I tried to basically replace preg_match with preg_replace but no cigar.
Following Gordon's reference, this gives:
$bad = array_merge(
array_map('chr', range(0,31)),
array("<", ">", ":", '"', "/", "\\", "|", "?", "*"));
$result = str_replace($bad, "", $filename);

Categories