preg_replace different result between sql result and string - php

I have a strange problem with a simple preg_replace, if I use
$pattern = '/<div class="formula">(.*?)<\/div>/';
$str = preg_replace($pattern, "", $str);
not work correctly, nothing is replaced....if I put a static string instead of $str all work correctly.
string(2133) "Velocità: <div class="formulaTex">...</div><div class="formula">...</div>
why?there is some kind of encoding to use?
if I pass the var to preg_replace not work, if I pass the static string it work!
this is my code:
$db = new PDO('sqlite:ARGOMENTI_NEW.sqlite');;
$result = $db->query("SELECT * FROM Testi WHERE IDSezione = 100");
while($row = $result->fetchAll(PDO::FETCH_ASSOC)){
$pattern = '/<div class="formula">(.*?)<\/div>/';
$str = preg_replace($pattern, "", $row[0]["Testo"]);
echo $str . "<br/><br/><br/>";
}
thanks

I find the error, the string from sql query stamp encoded html entity, on the screen I see the correct string but real string have different characters....this is the problem! whit this I solve:
$str = preg_replace( "/\r|\n/", "", html_entity_decode($row[0]["Testo"]));

Related

Ansvered / How to use content from database in PHP functions?

I have a PHP function which converts #Hashtag into a link...
function convertHashtags($str) {
$regex = "/#+([a-zA-Z0-9_]+)/";
$str = preg_replace($regex, '$0', $str);
return($str);
}
It work properly when I use it with a common string
$string = "Hello #World";
$string = convertHashtags($string);
(in this case an output would be: Hello #World
But when I'm trying to insert something from my database to that string it displays, but without that function's effect…
$string = $row["content"];
$string = convertHashtags($string);
(an output: Hello #World)
I am new to the PHP and MySQL stuff… Certainly, there are many things I don't know yet :D
What's wrong with this function?
Thanks!
function convertHashtags($str){
list($str1, $str2) = explode("#", $str) ;
$str2 = '#'.$str2.'';
$str = $str1." ".$str2 ;
return($str);
}
Can you use the above function and test with database entry?
Oh well, I just add new element to a database and it works!
I was testing it on old elements, they was inserted before I wrote the function.
I should try it before writing a this, my bad… thanks for help anyway!
$string = $row["content"];
$string = (string)$string;
$string = convertHashtags($string);
Use the above code and it will work.

PHP preg_replace url get parameters in string

Thanks to #s.d.a.p.e I've come a step close but I'm not quite there yet.
What I'm trying to do is replace all instances of a string in a block of text. I want to replace something like this:
user is ?user_id=34&first_name=Ralph so is ?user_id=1 also
With this:
user is /user/34/ so is /user/1/ also
Here is the preg_replace code I'm using:
$pattern = '#\?user_id=([0-9]+)#';
$replace = '/user/$1/';
echo preg_replace($pattern,$replace,$string);
With that pattern I end up with this:
user is /user/34/&first_name=Ralph so is /user/1/ also
Thanks again.
try this:
$string = "user is ?user_id=34&first_name=Ralph so is ?user_id=1 also";
$result = preg_replace('/\?(user)_id=(\d+)(.*?)(?! )/i', '/$1/$2/$3', $string );
echo $result ;
Output:
user is /user/34/&first_name=Ralph so is /user/1/ also
DEMO
I'd use this:
$string = 'user is ?user_id=34&first_name=Ralph so is ?user_id=1 also';
$pattern = '#\?user_id=([0-9]+)\S*#';
$replace = '/user/$1/';
echo preg_replace($pattern, $replace, $string);
Where \S stands for any character that is not a space.
Output:
user is /user/34/ so is /user/1/ also
print preg_replace(
'#\?user_id=([0-9]+)\&(first_name=(?:.*))#',
'/user/$1?$2',
'?user_id=34&first_name=Ralph'
);
result :
/user/34?first_name=Ralph if get it right..

PHP mb_eregi_replace does not work

I am trying to match a whole UTF-8 word in PHP. This is how I am trying to do it:
<?php
$string = 'DS DAMAT TAKIM ELBİSE (GOLD)';
$search = 'takım elbise';
$replace = 'TakımElbise';
$result = mb_eregi_replace('/\b'.$search.'\b/ui', $replace, $string);
echo $result;
echo preg_match('/\b'.$search.'\b/ui', $replace);
?>
But it does not work. What can be the problem?
NOTE:
I have tried adding these lines at the beginning of script:
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
No result.
How about:
$string = 'DS DAMAT TAKIM ELBİSE (GOLD)';
// ^__ this isn't an I
$search = 'takım elbİse';
// ^__ this isn't an I
$replace = 'TakımElbise';
$result = preg_replace("/\b$search\b/ui", $replace, $string);
echo $result;
I've just change the i to İ in the search string. You may want to use lowercase (I haven't on my keyboard)
See the comment here: http://php.net/manual/en/function.mb-ereg-replace.php
Unlike preg_replace, mb_ereg_replace doesn't use separators
Example with preg_replace:
$data = preg_replace("/[^A-Za-z0-9\.\-]/","",$data);
Example with mb_ereg_replace:
$data = mb_ereg_replace("[^A-Za-z0-9\.\-]","",$data);
Also, don't use the ui flags.

Replace a specified portion of a string

How can I use str_replace method for replacing a specified portion(between two substrings).
For example,
string1="www.example.com?test=abc&var=55";
string2="www.example.com?test=xyz&var=55";
I want to replace the string between '?------&' in the url with ?res=pqrs&. Are there any other methods available?
You could use preg_replace to do that, but is that really what you are trying to do here?
$str = preg_replace('/\?.*?&/', '?', $input);
If the question is really "I want to remove the test parameter from the query string" then a more robust alternative would be to use some string manipulation, parse_url or parse_str and http_build_query instead:
list($path, $query) = explode('?', $input, 2);
parse_str($query, $parameters);
unset($parameters['test']);
$str = $path.'?'.http_build_query($parameters);
Since you're working with URL's, you can decompose the URL first, remove what you need and put it back together like so:
$string1="www.example.com?test=abc&var=55";
// fetch the part after ?
$qs = parse_url($string1, PHP_URL_QUERY);
// turn it into an associative array
parse_str($qs, $a);
unset($a['test']); // remove test=abc
$a['res'] = 'pqrs'; // add res=pqrs
// put it back together
echo substr($string1, 0, -strlen($qs)) . http_build_query($a);
There's probably a few gotchas here and there; you may want to cater for edge cases, etc. but this works on the given inputs.
Dirty version:
$start = strpos($string1, '?');
$end = strpos($string1, '&');
echo substr($string1, 0, $start+1) . '--replace--' . substr($string1, $end);
Better:
preg_replace('/\?[^&]+&/', '?--replace--&', $string1);
Depending on whether you want to keep the ? and &, the regex can be mofidied, but it would be quicker to repeat them in the replaced string.
Think of regex
<?php
$string = 'www.example.com?test=abc&var=55';
$pattern = '/(.*)\?.*&(.*)/i';
$replacement = '$1$2';
$replaced = preg_replace($pattern, $replacement, $string);
?>

How to convert a string with numbers and spaces into an int

I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);

Categories