PHP find data within symbols - php

I am writing a program in PHP, and i need to find data that is in between two sets of symbols, and convert that to a string. For example
$main = "Hello, everyone, my name is (-Jack-)"
$string = regex_function('(-', $main) #should return "Jack"
How do i get that output, using a regex function or something

Try this :
$main = 'Hello, everyone, my name is (-Jack-)';
preg_match_all('/\(\-(?P<name>.*)\-\)/', $main, $matches);
echo "<pre>";
print_r($matches);
echo $matches['name'][0];

The function is known as preg_match_all().
$main = "Hello, everyone, my name is (-Jack-)";
preg_match_all('/\(\-(?P<name>\w+)\-\)/', $main, $string);
print_r( $string );
A sample output on codepad.
Referring to #Prasanth's comment; here's a better regex.
$main = "Hello, everyone, my name is (-Jack stuff-) some more text (-John stuff-)";
preg_match_all('/\(\-(?P<name>[\s\w]+)\-\)/', $main, $string);
print_r( $string );
Codepad link.

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.

How to make multiple preg_match

How do I make multiple preg_match on a string. I did a research and able to come out with below solutions.
<?php
$input = '#Hello# & Good Day ~World~';
$regex = '/
~
(.*?)
~
/six';
$input_new = preg_replace($regex,'<i>$1</i>', $input);
echo $input_new;
the above will search for (~)string(~) and change to italic format. How do I want to make the search for (#)string(#) and change to bold format on the same text.
preg_replace, as the manual says, can also take more than one pattern and replacement:
<?php
$input = '#Hello# & Good Day ~World~';
$regexes = array('/~(.*?)~/six',
'/#(.*?)#/six'
);
$replaces = array('<i>$1</i>',
'<b>$1</b>'
);
$input_new = preg_replace($regexes, $replaces, $input);
echo $input_new;
You do the same thing you did above, only this Time changing to and to like so. Otherwise, just create a Function to do that like so:
<?php
function transposeBoldItalic($inputString, $embolden="Hello",$italicise="World"){
$result = preg_replace("#(" . preg_quote($embolden) . ")#", "<strong>$1</strong>", $inputString);
$result = preg_replace("#(" . preg_quote($italicise) . ")#", "<em>$1</em>", $result);
return $result;
}
// TEST IT:
$inputString = "Hello & Good Day World";
var_dump(transposeBoldItalic($inputString, "Hello", "World"));
echo(transposeBoldItalic($inputString, "Hello", "World"));
// DUMPS
<strong>Hello</strong> & Good Day <em>World</em>
Test it Here: https://eval.in/571784
#osnapitzkindle answer is correct, but you can also use preg_replace_callback
echo preg_replace_callback('/([#~])(.*?)([#~])/', function ($matches){
return (strpos($matches[1], '#') !== false) ? "<i>{$matches[2]}</i>" : "<b>{$matches[2]}</b>";}, $input
);
Ideone Demo

How to extract certain text from a string

I've string like this:
hi my best friend #John How Are You?
I want to extract the name from the string:
john
This string has only one name it can be any number of names the string will have. I want to fetch the string between # and [space].
I've tried using explode() and foreach() loop, but I'm not able to get this value.
$text = "hi my best friend #John How Are You?";
preg_match_all("/(#\w+)/", $text, $matches);
var_dump( $matches );
try this
<?php
$string="hi my best friend #John How Are You?";
preg_match('/(?<=hi my best friend #)\S+/i', $string, $match);
echo $match[0];
Output
Jhon
Try this,
$string = "hi my best friend #John How Are You?";
$arr = explode(" ",$string);
foreach($arr as $val){
if (strpos($val,'#') !== false) {
$result = str_replace("#","",$val);
}
}
echo $result;
The regular expression will do fine but if you still want to do this using explode() and loop you may try the following code :-
$str="Hello my name is #John and this is my friend #julia";
$exp=explode(" ",$str);//exploding string from space
foreach($exp as $key=>$val){
if(strpos($val,"#")===false){continue;
}
else{$new[$k]=str_replace("#","",$val);}
}
print_r($new);
Hope this might help you.
Here is a quick working example
$string = "hi my best friend #John How Are You?";
$explodedstring = explode('#', $string);
$explodedforspace = explode(' ',$explodedstring[1]);
echo $explodedforspace[0];
?>

replacing letters with numbers

So i've been trying to get this bit of code to work all day and haven't been able to do it... I wnat to be able to replace letters with a number (or just a value) from an array. this is the code i've got:
$l2n =
array(
'a'=>'1',
'b'=>'2',
'c'=>'3',
'd'=>'4',
'e'=>'5',
'f'=>6,
'g'=>7,
'h'=>8,
'i'=>9,
'j'=>10,
'k'=>11,
'l'=>12,
'm'=>13,
'n'=>14,
'o'=>15,
'p'=>16,
'q'=>17,
'r'=>18,
's'=>19,
't'=>20,
'u'=>21,
'v'=>22,
'w'=>23,
'x'=>24,
'y'=>25,
'z'=>16
);
$string = str_split($string);
$explode = array_shift($string);
if($l2n[$explode] == $explode)
{
echo $l2n[$explode];
}
else
{
echo $l2n['a'];
}
I tried to use Preg_replace but i've never had a good expereince with that function. so If anybody could help me out, hint me in the correct direction, that'd be great.
You can just use str_replace once you've used array_keys and array_values to get each side of the array:
$keys = array_keys($l2n);
$values = array_values($l2n);
$yourstring = 'Hello world!';
echo str_replace($keys, $values, $yourstring);
// H5121215 231518124!
Demo: https://eval.in/77453
Docs:
http://php.net/str_replace
http://php.net/array_keys
http://php.net/array_values
You can simply do:
$string = preg_replace(array_keys($l2n), array_values($l2n), $string);
From the documentation:
If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart.
Why in the world would you use an array for this? Isn't ord() what you are looking for here?
$string = "ABCDE";
foreach ( str_split($string) as $chr ) {
echo ord($chr) - 64; // or 97 if they all are lowercase
echo PHP_EOL;
}

PHP read everything until first comma

I have string that will look like this:
$string = "hello, my, name, is, az";
Now I just wanna echo whatever is there before first comma. I have been using following:
echo strstr($this->tags, ',', true);
and It has been working great, but the problem it only works php 5.3.0 and above. I am currently on PHP 5.2.
I know this could be achieve through regular express by pregmatch but I suck at RE.
Can someone help me with this.
Regards,
<?php
$string = "hello, my, name, is, az";
echo substr($string, 0, strpos($string, ','));
You can (and should) add further checks to avoid substr if there's no , in the string.
Use explode than,
$arr = explode(',', $string,2);
echo $arr[0];
You can explode this string using comma and read first argument of array like this
$string = "hello, my, name, is, az";
$str = explode(",", $string, 2);
echo $str[0];
$parts = explode(',',$string);
echo $parts[0];
You can simple use the explode function:
$string = "hello, my, name, is, az";
$output = explode(",", $string);
echo $output[0];
Too much explosives for a small work.
$str = current(explode(',', $string));

Categories