I'm new in PHP. I've this format of strings ####CONTENT-21#### including different ids from content table in my page description section of page table. Just I need to separate the id numbers only & call contents from content table. how can I separate the numbers from the specific format ####CONTENT-21#### of string?
$string = '####CONTENT-21####';
$newnumber = filter_var($string, FILTER_SANITIZE_NUMBER_INT);
//if the number is preceeded by a (-) it will also get the (-) so trim the first char
ltrim($newnumber, '-');
First Case
If you are sure that all strings start with ####CONTENT- and end with #### you can get the numbers between with the following code, assuming $str is your string and $id is where you will store your ID.
$id = substr($str,12,strlen($str)-16);
Second Case
If you are not sure about the position of the id, but you are sure that ID is the only number in the string, you can match it with regular expression, assuming $str is your string and $id is where you will store your ID.
preg_match_all('!\d+!', $con_string, $matches);
$id = implode(' ', $matches[0]);
Related
I have a string as : ABSOLUTEWORKLEADSTOSUCCESS
I have another string as : '+'
Now how can I insert the second string at various indexes lets say (3,6,9) of the first string.
PS: I know how to do it via substr(). What i am looking for is something using regex/preg_replace()
Disclaimer: I think that the solution below is stupid, but it does exactly what you ask for: inserts a plus sign at specific indexes using a regular expression and preg_replace function:
<?php
// find 3 groups: three first symbols, two after them, and two more
// find the pattern from the beginning of a string
$regex = '/^(.{3})(.{2})(.{2})/';
$str = 'ABSOLUTEWORKLEADSTOSUCCESS';
// perform a replace: use first group (3 symbols), insert a plus
// then use a second group (2 symbols) and insert another plus,
// then use a third group (2 more symbols) and insert the last plus
$out = preg_replace($regex, '$1+$2+$3+', $str);
echo $out;
Preview here.
You can't insert string with preg_replace, for that you need to loop through the indexes and insert second string at specific index by using substr_rplace as follow
$var = 'ABSOLUTEWORKLEADSTOSUCCESS';
$indexes = array(3,6,9);
$newString = $var;
foreach($indexes as $key=>$value) {
$newString = substr_replace($newString, '+', $value+$key, 0) . "\n";
}
echo $newString;
check output here : https://eval.in/714177
I have a string
$string = "2.5 lakh videos views 0.8";
Now I want to get "0.8" from above string using PHP.
To get the last 3 characters:
$string = "2.5 lakh videos views 0.8";
$valSubstr = substr($string, -3);
echo $valSubstr;
To get the last "part" of the sentence. (this way you don't have to care about the count of characters in your number)
$string = "2.5 lakh videos views 0.8";
$partsString = explode(' ', $string);
$valExplode = $partsString[count($partsString) - 1];
echo $valExplode;
Both methods are bad, because you can only hope your data is in the format you expect it to be. But if your data is always in the format you showed, it would work. You can add a regex to check for unwanted characters like a trailing ".".
You can use php function substr() like this substr($string,-3);.
I am trying to use certain words in a array called keywords, which will be used to be replaced in a string by "as".
for($i = 0; $i<sizeof($this->keywords[$this->lang]); $i++)
{
$word = $this->keywords[$this->lang][$i];
$a = preg_replace("/\b$word\b/i", "as",$this->code);
}
It works with if I replace the variable $word with something like /\bhello\b/i, which then would replace all hello words with "as".
Is the approach am using even possible?
Before to be a pattern, it's a double quoted string, so variables will be replaced, it's not the problem.
The problem is that you use a loop to change several words and you store the result in $a:
the first iteration, all the occurences of the first word in $this->code are replaced and the new string is stored in $a.
but the next iteration doesn't reuse $a as third parameter to replace the next word, but always the original string $this->code
Result: after the for loop $a contains the original string but with only the occurences of the last word replaced with as.
When you want to replace several words with the same string, a way consists to build an alternation: word1|word2|word3.... It can easily be done with implode:
$alternation = implode('|', $this->keywords[$this->lang]);
$pattern = '~\b(?:' . $alternation . ')\b~i';
$result = preg_replace($pattern, 'as', $this->code);
So, when you do that, the string is parsed only once and all the words are replaced in one shot.
If you have a lot of words and a very long string:
Testing a long alternation has a significant cost. Even if the pattern starts with \b that highly reduces the possible positions for a match, your pattern will have hard time to succeed and more to fail.
Only in this particular case, you can use this another way:
First you define a placeholder (a character or a small string that can't be in your string, lets say §) that will be inserted in each positions of word boundaries.
$temp = preg_replace('~\b~', '§', $this->code);
Then you change all the keywords like this §word1§, §word2§ ... and you build an associative array where all values are the replacement string:
$trans = [];
foreach ($this->keywords[$this->lang] as $word) {
$trans['§' . $word . '§'] = 'as';
}
Once you have do that you add an empty string with the placeholder as key. You can now use the fast strtr function to perform the replacement:
$trans['§'] = '';
$result = strtr($temp, $trans);
The only limitation of this technic is that it is case-sensitive.
it will work if you keep it like bellow:
$a = preg_replace("/\b".$word."\b/i", "as",$this->code);
I thought I had this working; however after further evaluation it seems it's not working as I would have hoped it was.
I have a query pulling back a string. The string is a comma separated list just as you see here:
(1,145,154,155,158,304)
Nothing has been added or removed.
I have a function that I thought I could use preg_match to determine if the user's id was contained within the string. However, it appears that my code is looking for any part.
preg_match('/'.$_SESSION['MyUserID'].'/',$datafs['OptFilter_1']))
using the same it would look like such
preg_match('/1/',(1,145,154,155,158,304)) I would think. After testing if my user id is 4 the current code returns true and it shouldn't. What am I doing wrong? As you can see the id length can change.
It's better to have all your IDs in an array then checking if a desired ID is existed:
<?php
$str = "(1,145,154,155,158,304)";
$str = str_replace(array("(", ")"), "", $str);
$arr = explode(',', $str);
if(in_array($_SESSION['MyUserID'], $arr))
{
// ID existed
}
As your string - In dealing with Regular Expressions, however it's not recommended here, below regex will match your ID if it's there:
preg_match("#[,(]$ID[,)]#", $str)
Explanations:
[,(] # a comma , or opening-parenthesis ( character
$ID # your ID
[,)] # a comma , or closing-parenthesis ) character
I got now a two sides that contains numbers and between two specific numbers there is a string that shows a group of numbers, Let's say we got this 123456789$numbers1234567 and I want to get the result of $numbers so how can I get it?
Thanks
If you know the two strings that it is sandwiched between then you can strip out the strings that you are looking for.
Not too elegant but this works:
$str1 = "123456789";
$str2 = "1234567";
$numberstr = "123456789";
$searchstring = "123456789".$numberstr."1234567";
$limit = 1;
$numbers = substr($searchstring, 0, strlen($searchstring) - strlen($str2)); // Remove the end of the string with length = $str2
$numbers = substr($numbers, strlen($numbers) - strlen($str1)); // Remove the most string from the beginning
print $numbers;
Output:
123456789
In summary, it removes the known string from the end, then the other known string from the beginning.
UPDATE: as per the comments, use two substrs to find the wanted string