I have this link: http://www.youtube.com/e/fIL7Nnlw1LI&feature=related
I need a way in PHP to completely remove everything that is after EACH & in the link.
So it will become : http://www.youtube.com/watch?v=fIL7Nnlw1LI
Attention it could have more than one &
Everything after EACH &, & included, must be deleted from the string
How can I do it in PHP?
You can do this ::
$var = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related";
$url = explode("&", $var);
$url = $url[0]; //URL is now what you want, the part before First "&"
As I wrote in rpevious your question you can use this 1-line script:
$str = strtok($str,'&');
You can combine strpos with substr:
$spos = strpos($s, "&");
$initial_string = $spos ? substr($s, 0, $spos) : $s;
$url = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related";
$ampPos = strpos($var, '&');
if ($ampPos !== false)
{
$url = substr($url, 0, $ampPos);
}
Don't use explode, regexp or any other greedy algorithm, it's a waste of resources.
EDIT (Added performance information):
In the preg_match documentation: http://www.php.net/manual/en/function.preg-match.php
Tested explode myself with the following code:
$url = "http://www.youtube.com/e/fIL7Nnlw1LI&feature=related&bla=foo&test=bar";
$time1 = microtime(true);
for ($i = 0; $i < 1000000; $i++)
{
explode("&", $url);
$url = $url[0];
}
$time2 = microtime(true);
echo ($time2 - $time1) . "\n";
$time1 = microtime(true);
for ($i = 0; $i < 1000000; $i++)
{
$ampPos = strpos($url, "&");
if ($ampPos !== false)
$url = substr($url, 0, $ampPos);
}
$time2 = microtime(true);
echo ($time2 - $time1) . "\n";
Gave the following result:
2.47602891922
2.0289251804352
Look at the strpos function, that will give you where the first occurance of a character - in your case & is in a string. From that you can use substr to retrieve the piece of the string you want.
You can use the explode function () to split the string. $url = explode ( "&", $needle ) and then get the first array element.
Related
I have a string with this value:
$myValue = "1.099,90";
And I want to replace commas with dots and vice versa. Just like this:
$myNewValue = "1,099.90";
I know that there must be other better ways of doing this, but all I can get is:
$myNewValue = str_replace(",","|",$myValue);
$myNewValue = str_replace(".",",",$myValue);
$myNewValue = str_replace("|",".",$myValue);
This way looks weird and has a bad smell! Is there a cleaner way?
strtr() doesn't replace replacements, so you can avoid the temporary piping.
Code: (Demo)
$myValue = "7.891.099,90";
echo strtr($myValue, ".,", ",.");
// or
// echo strtr($myValue, ["." => ",", "," => "."]);
Output:
7,891,099.90
Resource: http://php.net/manual/en/function.strtr.php
This will get the job done, but you could definitely use preg_replace to come up with a different method as well.
<?php
$myValue = '1.099,90';
$parts = explode(".", $myValue); // break up the (.)periods
$num = count($parts); // number of parts
for($loop = 0; $loop < $num; $loop++){ // cycle through each part
if(strpos($parts[$loop], ",") !== false){ // if this includes (,)comma - swap it
$parts[$loop] = str_replace(",", ".", $parts[$loop]);
}
if($loop !== ($num - 1)){ // if this is not the last loop iteration..add comma after (replace period)
$myNewValue .= $parts[$loop] . ",";
} else {
$myNewValue .= $parts[$loop]; // last loop iteration, no comma at end
}
}
echo $myNewValue;
You can also use the str_replace w/ extra | symbol (or anything)...
<?php
$myValue = '1.099,90';
$replace = array(",", ".", "|");
$with = array("|", ",", ".");
$myNewValue = str_replace($replace, $with, $myValue);
echo $myNewValue;
?>
I want to parse and expand the given strings in PHP.
From
0605052&&-5&-7&-8
0605052&&-4&-7
0605050&&-2&-4&-6&-8
To
0605052, 0605053 ,0605054 ,0605055, 0605057, 0605058
0605052,0605053,0605054,0605057
0605050,0605051,0605052,0605054,0605056,0605058
can someone help me with that? thanks in advance!
Your question is not very clear, but I think you mean a solution like this:
Edited: Now the hole ranges were shown and not only the specified numbers.
<?php
$string = "0605052&&-5&-7&-8";
$test = '/^([0-9]+)\&+/';
preg_match($test, $string, $res);
if (isset($res[1]))
{
$nr = $res[1];
$test = '/\&\-([0-9])/';
preg_match_all($test, $string, $res);
$result[] = $nr;
$nrPart = substr($nr, 0, -1);
$firstPart = substr($nr, -1);
if (isset($res[1]))
{
foreach ($res[1] as &$value)
{
if ($firstPart !== false)
{
for ($i=$firstPart+1; $i<=$value; $i++)
{
$nr = $nrPart . $i;
$result[] = $nr;
}
$firstPart = false;
}
else
{
$nr = $nrPart . $value;
$result[] = $nr;
$firstPart = $value;
}
}
}
var_dump($result);
}
?>
This delivers:
result[0] = "0605052"
result[1] = "0605053"
result[2] = "0605054"
result[3] = "0605055"
result[4] = "0605057"
result[5] = "0605058"
I think a multi step approach is the best thing to do here.
E.g. take this as an example 0605052&&-5&-7&-8:
Split at -. The result will be 0605052&&, 5&, 7&, 8
The first result 0605052&& will help you create your base. Simply substring the numbers by finding first occurence of & and substring to the next to last number. Result will be 060505. You will also need the last number, so get it as well (which is 2 in this case).
Get the remaining ends now, all \d& are simple to get, simply take the first character of the string (or if those can be more than one number, use substring with first occurence of & approach again).
The last number is simple: it is 8.
Now you got all important values. You can generate your result:
The last number from 2., all numbers from 3. and the number from 4. together with your base are the first part. In addition, you need to generate all numbers from the last number of 2. and the first result of 3. in a loop by a step of 1 and append it to your base.
Example Code:
<?php
$str = '0605052&&-5&-7&-8';
$split = explode('-', $str);
$firstAmpBase = strpos($split[0], '&');
$base = substr($split[0], 0, $firstAmpBase - 1);
$firstEnd = substr($split[0], $firstAmpBase - 1, 1);
$ends = [];
$firstSingleNumber = substr($split[1], 0, strpos($split[1], '&'));
for ($i = $firstEnd; $i < $firstSingleNumber; $i++) {
array_push($ends, $i);
}
array_push($ends, $firstSingleNumber);
for ($i = 2; $i < count($split) - 1; $i++) {
array_push($ends, substr($split[$i], 0, strpos($split[$i], '&')));
}
array_push($ends, $split[count($split) - 1]);
foreach ($ends as $end) {
echo $base . $end . '<br>';
}
?>
Output:
0605052
0605053
0605054
0605055
0605057
0605058
Hi please check my code:
<?php
$length='';
//$username="stackoverflow";
//$username="php";
$username=$_REQUEST['parameter'];
$len = strlen($username)-2;
for($i=1; $i<=$len; $i++){
$length .= "*";
}
echo $username[0].$length.substr($username, -1);
?>
Above code i am using this code is working fine. But i need to customize code.
EX- if i use stackoverflow it should be s***********w and php should be p*p
My code is working but i need to any shortcut function to customize my php code. Share your knowledge
Thanks
Your best bet is to combine strlen() with str_repeat() and substr() for the beginning and ending character. Such a function could look like this:
function obfuscate_username($username) {
if (strlen($username) < 3) {
return $username;
}
else {
return substr($username, 0, 1).str_repeat('*', strlen($username)-2).substr($username, -1);
}
}
$username=$_REQUEST['parameter'];
echo substr($username,0,1).str_repeat("*",strlen($username)-2).substr($username,-1);
Fiddle
$a = "stackoverflow";
echo substr_replace($a, str_repeat("*", strlen($a)-2), 1,strlen($a)-2);
you can try this
<?php
$str = "stackoverflow";
$len = strlen($str);
if($len>=3)
{
$new_str = $str[0].str_repeat("*", $len-2).$str[$len-1];
}
else
{
$new_str = $str;
}
echo $new_str;
?>
Example
Get length of string:
$length = strlen($string);
Get first and last character:
$first = substr("abcdef", 0, 1);
$last = substr("abcdef", -1);
Create middle of the string:
$middle = str_repeat("*", $length-2);
Final get whole string:
return $first.$middle.$last;
Simple and easy: $username[0] adds the first character, str_repeat adds a character n times and username[$len - 1] adds the last character of your string.
$username = $_REQUEST["parameter"];
$len = strlen($username);
if ($len >= 2)
return $username[0] . str_repeat("*", $len - 2) . $username[$len - 1];
else
return $username;
Firstly, I want to inform that, what I need is the reverse of in_array PHP function.
I need to search all items of array in the string if any of them found, function will return true otherwise return false.
I need the fastest solution to this problem, off course this can be succeeded by iterating the array and using the strpos function.
Any suggestions are welcome.
Example Data:
$string = 'Alice goes to school every day';
$searchWords = array('basket','school','tree');
returns true
$string = 'Alice goes to school every day';
$searchWords = array('basket','cat','tree');
returns false
You should try with a preg_match:
if (preg_match('/' . implode('|', $searchWords) . '/', $string)) return true;
After some comments here a properly escaped solution:
function contains($string, Array $search, $caseInsensitive = false) {
$exp = '/'
. implode('|', array_map('preg_quote', $search))
. ($caseInsensitive ? '/i' : '/');
return preg_match($exp, $string) ? true : false;
}
function searchWords($string,$words)
{
foreach($words as $word)
{
if(stristr($string," " . $word . " ")) //spaces either side to force a word
{
return true;
}
}
return false;
}
Usage:
$string = 'Alice goes to school every day';
$searchWords = array('basket','cat','tree');
if(searchWords($string,$searchWords))
{
//matches
}
Also take note that the function stristr is used to make it not case-sensitive
As per the example of malko, but with properly escaping the values.
function contains( $string, array $search ) {
return 0 !== preg_match(
'/' . implode( '|', preg_quote( $search, '/' ) ) . '/',
$string
);
}
If string can be exploded using space following will work:
var_dump(array_intersect(explode(' ', $str), $searchWords) != null);
OUTPUT: for 2 examples you've provided:
bool(true)
bool(false)
Update:
If string cannot be exploded using space character, then use code like this to split string on any end of word character:
var_dump(array_intersect(preg_split('~\b~', $str), $searchWords) != null);
There is always debate over what is faster so I thought I'd run some tests using different methods.
Tests Run:
strpos
preg_match with foreach loop
preg_match with regex or
indexed search with string to explode
indexed search as array (string already exploded)
Two sets of tests where run. One on a large text document (114,350 words) and one on a small text document (120 words). Within each set, all tests were run 100 times and then an average was taken. Tests did not ignore case, which doing so would have made them all faster. Test for which the index was searched were pre-indexed. I wrote the code for indexing myself, and I'm sure it was less efficient, but indexing for the large file took 17.92 seconds and for the small file it took 0.001 seconds.
Terms searched for included: gazerbeam (NOT found in the document), legally (found in the document), and target (NOT found in the document).
Results in seconds to complete a single test, sorted by speed:
Large File:
0.0000455808639526 (index without explode)
0.0009979915618897 (preg_match using regex or)
0.0011657214164734 (strpos)
0.0023632574081421 (preg_match using foreach loop)
0.0051533532142639 (index with explode)
Small File
0.000003724098205566 (strpos)
0.000005958080291748 (preg_match using regex or)
0.000012607574462891 (preg_match using foreach loop)
0.000021204948425293 (index without explode)
0.000060625076293945 (index with explode)
Notice that strpos is faster than preg_match (using regex or) for small files, but slower for large files. Other factors, such as the number of search terms will of course affect this.
Algorithms Used:
//strpos
$str = file_get_contents('text.txt');
$t = microtime(true);
foreach ($search as $word) if (strpos($str, $word)) break;
$strpos += microtime(true) - $t;
//preg_match
$str = file_get_contents('text.txt');
$t = microtime(true);
foreach ($search as $word) if (preg_match('/' . preg_quote($word) . '/', $str)) break;
$pregmatch += microtime(true) - $t;
//preg_match (regex or)
$str = file_get_contents('text.txt');
$orstr = preg_quote(implode('|', $search));
$t = microtime(true);
if preg_match('/' . $orstr . '/', $str) {};
$pregmatchor += microtime(true) - $t;
//index with explode
$str = file_get_contents('textindex.txt');
$t = microtime(true);
$ar = explode(" ", $str);
foreach ($search as $word) {
$start = 0;
$end = count($ar);
do {
$diff = $end - $start;
$pos = floor($diff / 2) + $start;
$temp = $ar[$pos];
if ($word < $temp) {
$end = $pos;
} elseif ($word > $temp) {
$start = $pos + 1;
} elseif ($temp == $word) {
$found = 'true';
break;
}
} while ($diff > 0);
}
$indexwith += microtime(true) - $t;
//index without explode (already in array)
$str = file_get_contents('textindex.txt');
$found = 'false';
$ar = explode(" ", $str);
$t = microtime(true);
foreach ($search as $word) {
$start = 0;
$end = count($ar);
do {
$diff = $end - $start;
$pos = floor($diff / 2) + $start;
$temp = $ar[$pos];
if ($word < $temp) {
$end = $pos;
} elseif ($word > $temp) {
$start = $pos + 1;
} elseif ($temp == $word) {
$found = 'true';
break;
}
} while ($diff > 0);
}
$indexwithout += microtime(true) - $t;
try this:
$string = 'Alice goes to school every day';
$words = split(" ", $string);
$searchWords = array('basket','school','tree');
for($x = 0,$l = count($words); $x < $l;) {
if(in_array($words[$x++], $searchWords)) {
//....
}
}
Below prints the frequency of number of elements found from the array in the string
function inString($str, $arr, $matches=false)
{
$str = explode(" ", $str);
$c = 0;
for($i = 0; $i<count($str); $i++)
{
if(in_array($str[$i], $arr) )
{$c++;if($matches == false)break;}
}
return $c;
}
Below link will help you : just need to customize as you required.
Check if array element exists in string
customized:
function result_arrayInString($prdterms,208){
if(arrayInString($prdterms,208)){
return true;
}else{
return false;
}
}
This may be helpful to you.
I have a string that looks like this:
$str = "bla_string_bla_bla_bla";
How can I remove the first bla_; but only if it's found at the beginning of the string?
With str_replace(), it removes all bla_'s.
Plain form, without regex:
$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
if (substr($str, 0, strlen($prefix)) == $prefix) {
$str = substr($str, strlen($prefix));
}
Takes: 0.0369 ms (0.000,036,954 seconds)
And with:
$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);
Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.
Profiled on my server, obviously.
You can use regular expressions with the caret symbol (^) which anchors the match to the beginning of the string:
$str = preg_replace('/^bla_/', '', $str);
function remove_prefix($text, $prefix) {
if(0 === strpos($text, $prefix))
$text = substr($text, strlen($prefix)).'';
return $text;
}
Here's an even faster approach:
// strpos is faster than an unnecessary substr() and is built just for that
if (strpos($str, $prefix) === 0) $str = substr($str, strlen($prefix));
Here.
$array = explode("_", $string);
if($array[0] == "bla") array_shift($array);
$string = implode("_", $array);
In PHP 8+ we can simplify using the str_starts_with() function:
$str = "bla_string_bla_bla_bla";
$prefix = "bla_";
if (str_starts_with($str, $prefix)) {
$str = substr($str, strlen($prefix));
}
https://www.php.net/manual/en/function.str-starts-with.php
EDIT: Fixed a typo (closing bracket) in the example code.
Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version? – toddmo Jun 29 at 23:26
A general version:
$parts = explode($start, $full, 2);
if ($parts[0] === '') {
$end = $parts[1];
} else {
$fail = true;
}
Some benchmarks:
<?php
$iters = 100000;
$start = "/aaaaaaa/bbbbbbbbbb";
$full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee";
$end = '';
$fail = false;
$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
if (strpos($full, $start) === 0) {
$end = substr($full, strlen($start));
} else {
$fail = true;
}
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "strpos+strlen", $t);
$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
$parts = explode($start, $full, 2);
if ($parts[0] === '') {
$end = $parts[1];
} else {
$fail = true;
}
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "explode", $t);
On my quite old home PC:
$ php bench.php
Outputs:
strpos+strlen : 0.158388 s
explode : 0.126772 s
Lots of different answers here. All seemingly based on string analysis. Here is my take on this using PHP explode to break up the string into an array of exactly two values and cleanly returning only the second value:
$str = "bla_string_bla_bla_bla";
$str_parts = explode('bla_', $str, 2);
$str_parts = array_filter($str_parts);
$final = array_shift($str_parts);
echo $final;
Output will be:
string_bla_bla_bla
Symfony users can install the string component and use trimPrefix()
u('file-image-0001.png')->trimPrefix('file-'); // 'image-0001.png'
I think substr_replace does what you want, where you can limit your replace to part of your string:
http://nl3.php.net/manual/en/function.substr-replace.php (This will enable you to only look at the beginning of the string.)
You could use the count parameter of str_replace ( http://nl3.php.net/manual/en/function.str-replace.php ), this will allow you to limit the number of replacements, starting from the left, but it will not enforce it to be at the beginning.