Removing url / domain from string with parentheses - php

Is there any way to find and remove the url or domain from given string with parentheses ?
example: (like someurl.com) should be (like) and [like someurl.com] to become [like] ... also [like someurl.com/path/something.html] should be [like]
maybe someone can help me with a code to do this.

You need a Regular Expression (regx) here
$string_with_url = 'lorem (like GOoogle.COM someurl.com/path/something.html ) lipsum';
$string_without_url = preg_replace("/(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-zA-Z0-9]+([\-\.]{1}[a-zA-Z0-9]+)*\.[a-zA-Z]{2,5}(:[0-9]{1,5})?(\/.+[a-zA-Z\/]\s)?/", "", $string_with_url);
echo $string_without_url; // lorem (like ) lipsum

$str = "(like someurl.com)";
$index_dot = $index_space_before_dot = $index_after_dot = -1;
for($i=0; $i<strlen($str); $i++){
if($str[$i] == '.'){
$index_dot = $i;
}
if($str[$i] == ' ' && $index_dot == -1 && $index_space_before_dot == -1){
$index_space_before_dot = $i;
}elseif ($str[$i] == ' ' && $index_dot > -1){
$index_space_before_dot = $i;
}
}
$str = substr($str, 0, $index_space_before_dot);
echo $str . ')';

Related

how to change the color of decimals points in php

how can I change the colors of ONLY decimals of a number in PHP?
this is my function for formatting numbers
function formatNumber($input, $decimals = 'auto', $prefix = '', $suffix = '') {
$input = floatval($input);
$absInput = abs($input);
if ($decimals === 'auto') {
if ($absInput >= 0.01) {
$decimals = 2;
} elseif (0.0001 <= $absInput && $absInput < 0.01) {
$decimals = 4;
} elseif (0.000001 <= $absInput && $absInput < 0.0001) {
$decimals = 6;
} elseif ($absInput < 0.000001) {
$decimals = 8;
}
}
if($input>1000000000000000){
$result = ROUND(($input/1000000000000000),2).' TH ';
}elseif($input>1000000000000){
$result = ROUND(($input/1000000000000),2).' T ';
}elseif($input>1000000000){
$result = ROUND(($input/1000000000),2).' B ';
}elseif($input>1000000) {
$result = ROUND(($input / 1000000), 2) . ' M ';
} else {
$result = number_format($input, $decimals, config('decimal-separator','.'), config('thousand-separator', ',')) ;
}
return ($prefix ? $prefix : '') . $result. ($suffix ? $suffix : '');
}
and I use it like that
<?php echo formatNumber($chart['assist'], 2)?>
i want my decimals with a different color... can i use css there or add classes?
Here is an example of what I meant in my comment by manipulate the string:
<?php
$n = 123.456;
$whole = floor($n); // 123
$fraction = $n - $whole; // .456
//echo str_replace('.', '<span class="colorme">.</span>', $n);
echo $whole . '<span class="colorme">.</span>' . substr($fraction, strpos($fraction, '.')+1);
//Simply do a string replace on the decimal point.
UPDATED break out parts, concatenate.
A client side approach with Javascript (with some jQuery) would be something like:
$('#myDiv').each(function () {
$(this).html($(this).html().replace(/\./g, '<span class="colorme">.</span>'));
//or decimal point and decimal number part...
$(this).html($(this).html().replace(/\.([0-9]+)/g, '<span class="colorme">.$1</span>'));
});
Remember that other locales don't always use . for divider.
So with your existing code, you could do something like:
$dec_point = config('decimal-separator','.');
$wrapped_dec_point = "<span class='dec_point'>{$dec_point}</span>";
$result = number_format($input, $decimals, $wrapped_dec_point, config('thousand-separator', ',')) ;
and then of course, for your CSS, you would just need
.dec_point {
color: magenta;
}
Here is shorter solution
$n = 123.456;
$nums = explode(".",$n);
echo $nums[0] . '<span class="colorme">.' . $nums[1] . '</span>';

Unable to read blank spaces in string

What's wrong with this code. I want to read the number of blank spaces without using any built in function, but it wont return or read the blank spaces:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while ($string[$i] != '' & $string[$i + 1] != '') {
if ($string[$i] == "" || empty($string[$i])) {
die("cdsd");
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
It's always going into the else part and never goes into the if statement. I even tried using isset() but that also didn't work. Where am I making a mistake?
Just loop while the string offset isset() and check if it equals a space. No need to do anything with $i+1:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while (isset($string[$i])) {
if ($string[$i] == " ") {
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
This outputs:
canyoulookintothis??4
Once you've got your code right, you will always run into an string index error and you will need the isset() built in function to check before performing operations.
In other words, the i for the index will eventually point beyond the last letter of the string, this will cause a PHP error. You can use isset() to check for it and break out of the loop. Example:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while (isset($string[$i])) {
if ($string[$i] == " ") {
$breakPoints++;
} else {
if($string[$i] != ''){
print_r($string[$i]);
}
}
$i++;
}
echo("<br />Number of spaces: ".$breakPoints
spaces is not empty, it will tack size.
so use this
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while ($string[$i] != '' & $string[$i + 1] != '') {
if ($string[$i] == " ") {
echo " ";
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
DEMO
or try this code,
use preg_match_all.
$matches = " ";
$numSpaces = preg_match_all('/[ ]/', $string , $matches);
or Use this::
substr_count($string , ' ');

PHP - latex format of function with regex

Is it possible to write a regex which would take input like 'sqrt(2 * (2+2)) + sin(pi/6)' and transform it into '\sqrt{2 \cdot (2+2)} + \sin(\pi/6)'?
The problem is the 'sqrt' and parentheses in it. It is obvious I can't simply use something like this:
/sqrt\((.?)\)/ -> \\sqrt{$1}
because this code would create something like this '\sqrt{2 \cdot (2+2)) + \sin(\pi/6}'.
My solution: it simply go throw the string converted to char array and tests if a current substring starts with $latex, if it does second for-cycle go from this point in different direction and by parentheses decides where the function starts and ends. (startsWith function)
Code:
public static function formatFunction($function, $latex, $input) {
$input = preg_replace("/" . $function . "\(/", $latex . "{", $input);
$arr = str_split($input);
$inGap = false;
$gap = 0;
for ($i = count($arr) - 1; $i >= 0; $i--) {
if (startsWith(substr($input, $i), $latex)) {
for ($x = $i; $x < count($arr); $x++) {
if ($arr[$x] == "(" || $arr[$x] == "{") { $gap++; $inGap = true; }
else if ($arr[$x] == ")" || $arr[$x] == "}") { $gap--; }
if ($inGap && $gap == 0) {
$arr[$x] = "}";
$inGap = false;
break;
}
}
}
$gap = 0;
}
return implode($arr);
}
Use:
self::formatFunction("sqrt", "\\sqrt",
"sqrt(25 + sqrt(16 - sqrt(49)) + (7 + 1)) + sin(pi/2)");
Output:
\sqrt{25+\sqrt{16-\sqrt{49}}+(7+1)}+\sin (\pi/2)
Note: sin and pi aren't formated by this code, it's only str_replace function...
In general, no regular expression can effectively handle nested parentheses. Sorry to be the bearer of bad news! The MathJAX parser library can interpret LaTeX equations and you could probably add a custom output routine to do what you want.
For TeX questions, you can also try http://tex.stackexchange.com .
Some time ago i soved a similar problem in such way. Maybe it will be helpful for you
$str = 'sqrt((2 * (2+2)) + sin(pi/(6+7)))';
$from = []; // parentheses content
$to = []; // patterns for replace #<number>
$brackets = [['(', ')'], ['{', '}'], ['[', ']']]; // new parentheses for every level
$level = 0;
$count = 1; // count or replace made
while($count) {
$str = preg_replace_callback('(\(([^()]+)\))',
function ($m) use (&$to, &$from, $brackets, $level) {
array_unshift($to, $brackets[$level][0] . $m[1] . $brackets[$level][1]);
$i = '#' . (count($to)-1); // pattern for future replace.
// here it '#1', '#2'.
// Make it so they will be unique
array_unshift($from, $i);
return $i; }, $str, -1, $count);
$level++;
}
echo str_replace($from, $to, $str); // return content back
// sqrt[{2 * (2+2)} + sin{pi/(6+7)}]
I forgot all details, but it, seems, works

how to detect a whitespace on string in php program

I want to do treatments on two strings, and I must to know if there are spaces to stop my treatment and move on to the rest of characters
I tested that but it doesn't rule the problem :
for ($i = 0; $i < $lenght; $i++) {
if($text[$i] <> '' && $mask[$i] <> ''){
$nbrcrypted = $stringtonumber[$text[$i]] + $stringtonumber[$mask[$i]];
$resultat .= $numbertostring[$nbrcrypted];
}else{
$indice = false;
}
}
how can I achieve that, thank you in advance
if($text[$i] <> '' && $mask[$i] <> ''){ is useless, use if($text[$i] !== ' ' && $mask[$i] !== ' '){ for spaces
I don't get what you're actually trying to do but if you want to test your string for whitespaces:
if ( strpos( $yourString, ' ' ) !== false )
null; // string has whitespace(s)

Find answer to string equation without using eval()

I need a way of taking an equation given as a string and finding it's mathematical answer, the big caveat is that I can't use eval().
I know the equation will only ever contain numbers, the four mathematical operators (i.e. * / + -) and parentheses, it may or may not have spaces in the string. Here's a couple of examples.
4 * 4
4+6/3
(3 / 2)*(4+8)
(4+8) * 2
I'm guessing that it's going to have to be done with some kind of regex?
Math expressions aren't regular. They're context-free.
Your best bet is to parse them using well-known math parsing algorithms like the shunting yard algorithm. All you have to worry about is implementing the algorithm in PHP. You might even be able to find PHP implementations of it online.
Just in case anybody's interested here is the algorithm I came up with in PHP for producing Reverse Polish Notation
function convertToRPN($equation)
{
$equation = str_replace(' ', '', $equation);
$tokens = token_get_all('<?php ' . $equation);
$operators = array('*' => 1, '/' => 1, '+' => 2, '-' => 2);
$rpn = '';
$stack = array();
$size = count($tokens);
for($i = 1; $i < $size; $i++) {
if(is_array($tokens[$i])) {
$rpn .= $tokens[$i][1] . ' ';
} else {
if(empty($stack) || $tokens[$i] == '(') {
$stack[] = $tokens[$i];
} else {
if($tokens[$i] == ')') {
while(end($stack) != '(') {
$rpn .= array_pop($stack);
}
array_pop($stack);
} else {
while(!empty($stack) && end($stack) != '(' && $operators[$tokens[$i]] >= $operators[end($stack)]) {
$rpn .= array_pop($stack);
}
$stack[] = $tokens[$i];
}
}
}
}
while(!empty($stack)) {
$rpn .= array_pop($stack);
}
return $rpn;
}

Categories