how to parse str in variable - php

I am trying to parse following text in variable...
$str = 3,283,518(10,569 / 2,173)
And i am using following code to get 3,283,518
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]); //prints 3283518
the above $str is dynamic and sometimes it could be only 3,283,518(means w/o ()) so explode function will throw an error so what is the best way to get this value? thanks.

$str = "3,283,518(10,569 / 2,173)";
preg_match("/[0-9,]+/", $str, $res);
$match = str_replace(",", "", array_pop($res));
print $match;
This will return 3283518, simply by taking the first part of the string $str that only consists of numbers and commas. This would also work for just 3,283,518 or 3,283,518*10,569, etc.

Probably going to need more information from you about how dynamic $str really is but if its just between those values you could probably do the following
if (strpos($str, '(' ) !== false) {
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]);
} else {
//who knows what you want to do here.
}

If you are really sure about number format, you can try something like:
^([0-9]+,)*([0-9]+)
Use it with preg_match for example.
But if it is not a simple format, you should go with an arithmetic expressions parser.

Analog solution:
<?php
$str = '3,283,518(10,569 / 2,173)';
if (strstr($str, '('))
{
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]);
}
else
{
$num = str_replace(',','',$str);
}
echo $num;
?>

Related

Remove quotes from string inside of array

I have a string that looks like this:
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
I need to get rid of the " that are inside of the [] array so it looks like this:
$string = '"excludeIF":[miniTrack, tubeTrack, boxTrack]';
I was trying some regex but I kept getting rid of all of the quotes.
For this particular example:
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
preg_match("/((?<=\[).*(?=\]))/", $string, $match);
$change = str_replace('"', "", $match[0]);
$result = preg_replace("/$match[0]/", $change, $string);
What this does is it gets the content inside the square brackets, removes the quotes, then replaces the original content with the cleaned content.
This may run into errors if you have the exact same string outside of square brackets later on, but it should be an easy fix if you understand what I've written.
Hope it helps.
PS. It would also help if you showed us what regexes you were trying, as you were, perhaps, on the right path but just had some misunderstandings.
So yeah I agree with the comment about the XY Problem, but I would still like to try help.
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
You will now need to find the start and end positions of the string that you want edited. This can be done by the following:
$stringPosition1 = strpos($string,'[');
$stringPosition2 = strpos($string,']');
Now you have the correct positions you are able to do a substr() to find the exact string you want edited.
$str = substr($string,$stringPosition1,$stringPosition2);
From here you can do a simple str_replace()
$replacedString = str_replace('"','',$str);
$result = '"excludeIF":' . $replacedString;
It is an excellent idea to look at the PHP docs if you struggle to understand any of the above functions. I truly believe that you are only as good at coding as your knowledge of the language is. So please have a read of the following documents:
Str_pos: http://php.net/manual/en/function.strpos.php
Sub_str: http://php.net/manual/en/function.substr.php
Str_replace: http://php.net/manual/en/function.str-replace.php
test this code:
<?php
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
$str_array = str_split($string);
$string_new = '';
$id = 0;
foreach ($str_array as $value) {
if($value == '[' || $id != 0){
$id = ($value != ']') ? 1 : 0;
$string_new .= ($value != "\"") ? $value : '' ;
} else {
$string_new .= $value;
}
}
echo $string_new;
//RESULT "excludeIF":[miniTrack,isTriangleHanger,tubeTrack,boxTrack]
?>
Good luck!
EDIT
<?php
$string = '"excludeIF":["miniTrack","isTriangleHanger","tubeTrack","boxTrack"]';
$part = str_replace("\"","",(strstr($string,'[')));
$string = substr($string,0,strpos($string,'[')).$part;
echo $string;
?>
Other possible solution.
Fun with code!

Delete element in Array

I have some string:
It's not big deal
I want to change it to
It's not_big deal
So far, I try this code but return "undefined offset: $y"
function checkNegation($word){
$input = strtolower($word);
$split = preg_split('/\s+/', $input);
$length = count($split);
$neg = "NOT_";
for ($x=0; $x<$length; $x++){
if (preg_match("/\bNOT\b/i",$split[$x])){
$y=$x+1;
$split[$x] = "{$neg}{$split[$y]}";
unset($split[$y]);
}
}
$word = implode(" ",$split);
return $word;
}
can you help me? thank you :')
Why not just preg_replace?
$str = "It's not big deal";
echo preg_replace("/\b(not)\s+/i", "$1_", $str); // It's not_big deal
if you're using regex already, why do you need to break the string into array of words? you can just match "not" in it and replace it with "not_". why over-complicate things?
your program seems to be running fine. but it'll cause problem if the word "not" is the last word in the string. because in that case, $y will go out of array range.

How right print result search preg_replace inside fetch_assoc() result mysql?

$i = $result->fetch_assoc();
preg_replace("/\{(.*?)\}/", $i["$1"], $content);
Error - Undefined variable: $1
// $1 - 'string'; // result search preg_replace()
// $i['string'] = 'hello';
How right syntax will be for print 'hello'?
ok next time please spend a little more time on asking the question:
<?php
$i['string'] = 'zzzzzzzzzzzzzzzzzzzzzz';
$content = "test test test {string} testtesttesttesttest";
$x=preg_replace_callback("/\{(.*?)\}/", function($m) use($i){
return $i[$m[1]];
}, $content);
echo $x;
demo: http://codepad.viper-7.com/u29uKh
for this particular approach you need to use preg_replace_callback() requires PHP 5.3+
You can make your replacements faster using strtr. To do that, you only need an associative array, but this time, all keys must be enclosed between curly brackets.
$i = $result->fetch_assoc();
$keys = array_map(function($k) { return '{' . $k . '}'; }, array_keys($i));
$trans = array_combine($keys, $i);
$content = strtr($content, $trans);
A variable name can't start with a number in PHP. It must start with an underscore or letter.

how to get string between .ism and slash before it using php?

I have a large string and want to extract data between .ism and the slash / before it. For example I want to get: life-episode-galaxy
My current code gives all data before .ism. Could anyone tell me what is wrong here and how to get only data between .ism and slash / before it?
<?
$code="media=http://somesite.com/4534543kjlkljklkjlkkljlkdsfsfo/life-episode-galaxy.ism/manifest,deliverymethod=adaptiv";
$startsAt3 = strpos($code, "/") + strlen("/");
$endsAt3 = strpos($code, ".ism", $startsAt3);
$result3 = substr($code, $startsAt3, $endsAt3 - $startsAt3);
echo $result3;
?>
I Assume your link would have always the same number of slashes / you can just explode into an array and output the right element, removing the not needed data with str_replace
$code="media=http://somesite.com/4534543kjlkljklkjlkkljlkdsfsfo/life-episode-galaxy.ism/manifest,deliverymethod=adaptiv";
$array = explode("/", str_replace("//", "/", $code));
echo str_replace('.ism', '', $array[3]);
This will output
life-episode-galaxy
Live Sample
You could use a regexp, but that's boring.
You can use strrpos with the 3rd offset parameter, using a negative offset.
$ism_pos = strpos($code, ".ism");
$last_slash_pos_before_ism = strrpos($code, "/", $ism_pos - strlen($code));
$result = substr($code, $last_slash_pos_before_ism, $ism_pos);
Might be off-by-one here and there, check it.
I would use regex:
$pattern = '#/(.*)\.ism/#U';
$matches = array();
$found = preg_match($pattern, $string, $matches);
if (1 === $found) {
$your_desired_string = $matches[1];
} else {
// not found
}

Regex to transform abcd to (a(b(c(d))))

I'm using PHP's preg_replace, and trying to transform the string
abcd
into
(a(b(c(d))))
This is the best I've got:
preg_replace('/.(?=(.*$))/', '$0($1)', 'abcd');
// a(bcd)b(cd)c(d)d()
Is it even possible with regex?
Edit I've just discovered this in the PCRE spec: Replacements are not subject to re-matching, so my original approach isn't going to work. I wanted to keep it all regex because there's some more complicated matching logic in my actual use case.
How about:
preg_replace('/./s', '($0', 'abcd') . str_repeat(')', strlen('abcd'));
?
(Does that count as "with regex"?)
You can use preg_match_all. Not sure what kind of characters you want, though. So I'll give an example for all characters:
$val = 'abcd1234';
$out = '';
if(preg_match_all('#.#', $val, $matches))
{
$i = 0; // we'll use this to keep track of how many open paranthesis' we have
foreach($matches[0] as &$v)
{
$out .= '('.$v;
$i++;
}
$out .= str_repeat(")", $i);
}
else
{
// no matches found or error occured
}
echo $out; // (a(b(c(d(1(2(3(4))))))))
Will be easy to customise further, as well.
This is my way to do it =) :
<?php
$arr = str_split("abcd");
$new_arr = array_reverse($arr);
foreach ($new_arr as $a) {
$str = sprintf('(%s%s)', $a, $str);
}
echo "$str\n";
?>
KISS isn't it ? (few lines : 6)
I went with something along the lines of a combination of the above answers:
preg_match_all('/./ui', 'abcd', $matches);
$matches = $matches[0];
$string = '('.implode('(', $matches).str_repeat(')', count($matches));

Categories