alter word keeping the punctuation mark in its own position - php

I want a program in php that takes the first letter of word to the last and add "ay" at end. example:
I love my family becomes Iay ovelay ymay amilyfay
I did this to get my result:
<?php
$var = "I love my family";
$words = explode(" ",$var);
$final = "";
foreach ($words as $word){
$n = "";
for($i=1;$i<strlen($word);$i++){
$n .= $word{$i};
}
$n .= $word{0}."ay";
$final .= $n." ";
}
echo $final;
?>
but this doesnt work when the input is: he says, "I love my family". this gives output as: ehay ays,say I"ay ovelay ymay amily"fay where I need the punctuation marks to be in their own position like this: ehay ayssay, "Iay ovelay ymay amilyfay"
Tried alot but found nothing that works

Looks like something along the lines of:
$str = 'he says, "I love my family"';
$str = preg_replace('/(\w{1})(\w*)/', "$2$1ay", $str);
echo $str; // ehay ayssay, "Iay ovelay ymay amilyfay"
Should get you at least most of the way there.

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!

Get all of the text from a string after the first one sentence

So Currently I am using this code to get the first sentence only out of a string
preg_match('/^([^.!?]*[\.!?]+){0,1}/', $text, $abstract);
Can you please help me on how to create another regular expression to get the remaining text or get the text after the first sentence only ?
Thanks
This should give you the general idea using explode():
<?php
$string = 'Sentence one. Sentence two. Sentence three. Sentence four.';
$sentences = explode(".", $string);
echo $sentences[0]; // echos 'Sentence one'
echo $sentences[1]; // echos ' Sentence two'
echo $sentences[2]; // echos ' Sentence three'
echo $sentences[3]; // echos ' Sentence four'
// The following demonstrates how to do what you're asking, but I'm not quite
// sure what your specific use case is so adapt as necessary.
echo $sentences[0]; // echos 'Sentence one'
// to echo the remaining sentences do this
// start at 1 not 0 to skip the first sentence
for ($i = 1; $i < count($sentences); $i++)
{
echo $sentences[$i];
}
Note that this will treat any '.' as the end of a sentence so it may not be suitable in all cases, for example if you have 'I.T.' mid-sentence. Therefore the regular expression may be a more appropriate solution if you need this level of accuracy. Just let me know if you have any questions. : )
This might help you if you know how many sentences are exactly there in that string.
$str = "First Sentence.";
$str .= "Second Sentence. Third Sentence";
$result = explode(".",$str)[1].". ".explode(".",$str)[2];
echo $result;
UPDATE
Final Answer >>
$str = "First Sentence.";
$str .= "Second Sentence. Third Sentence";
$extract = strpos($str, ".")+1;
$result = substr($str, $extract, strlen($str));
echo $result;

Piglatin program in PHP without regular expressions?

Basically I'm trying to write a pretty basic program in PHP that just takes user input and translates it into Piglatin with PHP without using regular expressions. This is what my code so far looks like, which is fine:
<?php # script
$original = $_REQUEST['original'];
$array = explode(" ", $original);
$piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$thsh = substr($word,1,2);
$thshrest = substr($word,2, strlen($word)-2);
$rest = substr($word,1,strlen($word)-1);
if(trim($word))
{
$piglatin .= (strlen($word)==1)?$first." ":$rest.$first. "ay ";
}
}
echo $original ." becomes: ".$piglatin;
?>
except it doesn't take into account the special cases, like if a word begins with a vowel (in which case, the word "igloo" for example should be printed as "iglooway"), or if it begins with "th" or "sh" (in which case, the word "thimble" for example should be printed as "imblethay", taking the first two letters and bringing them to the end instead of just the first one.)
I've already started the process of creating variables out of the strings that start with "th" and "sh" (see $thsh and $thshrest), but I'm really confused as to where I should go from here?
A regex solution (probably not what you want, but I want to show just how easy it is):
$pig_latin = preg_replace('#^([^aeiou]+)([aeiou]+)(.*)#', '$2$3$1ay', $original);
$pig_latin = preg_replace('#(^[aeiou].*)#', '$1way', $pig_latin);
How about:
foreach ($array as $word) {
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1way", $word);
} else {
$word = preg_replace('/^(th|sh)(.+)$/', "$2$1ay", $word);
}
$piglatin .= $word ." ";
}

Link each word of string WITHOUT linking <br>

I'm using a PHP script to link each word of the string:
<?
$str = "hello<br> guys good man";
$arr = explode(' ', $str);
foreach($arr as $value){
echo ''.$value.'';
}
?>
How do I link each word of the string $str without linking the <br>s?
You can just use preg_replace
// More complext string
$str = "hello<br> guys good man Google <br /> hurry";
// Url Template
$template = '%1$s';
// Replace Words
echo preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b([a-z]+)\b/is", sprintf($template, "\\1"), $str);
Output
hello
<br>
guys
good
man
Google
<br />
hurry
Use the strip_tags() function before/in your explode:
$arr = explode (' ', strip_tags($str));
Untested, but start with JvO's code and put the links back into the original string:
$str = "hello<br> guys good man";
$arr = explode (' ', strip_tags($str));
foreach($arr as $value) {
$link = ''.$value.'';
$str = str_replace($value, $link, $str);
}
echo $str;
Note that you can save time by removing duplicates from $arr.
Edit: in fact, you must remove duplicates from $arr, or things will get ugly:
$arr = array_unique(explode (' ', strip_tags($str)));
... and another edit to the original code for an error.
Before you form the link, process the string first:
$proc_val = preg_replace('/<br>/', '', $value);
echo ''.$value.'';
Not sure what you were saying in the comment of Jvo's answer, but you can always use the striptags in the foreach as well and only strip the link part.
foreach($arr as $value){
echo ''.$value.'';
}
So here is the full code:
<?
$str = "hello<br> guys good man";
$arr = explode(' ', $str);
foreach($arr as $value){
echo ''.$value.'';
}
?>
You really should think about what explode(' ', $str) is going to do though.
Any time any HTML tag has attributes to it like <span style="color: red;"> you are going to run into trouble. You should strip_tags first, on the entire string, then process it. Keep an HTML version as a separate string if you need to add stuff later.
Why not just explode the string as you currently are and simply strip the tags in the URL.
$str = "hello<br> guys good man";
$arr = explode(' ', $str);
foreach($arr as $value){
echo ''.$value.'';
}
This will output the following HTML which is what I believe you want.
hello<br>
guys
good
man
If the string is quite long, and can contain any number of tags, including <p>, <h1> and <br> as well as the more correct <br/>, you could consider parsing the lot, and use str_replace:
$string = 'Foo<br/>Hello Bar!';
$DOM = new DOMDocument;
//make sure all breaks are preceded by a space, if not words might be concatenated by accident
$DOM->loadHTML(str_replace('<br', ' <br', $string));
//get all nodes
$nodes = $DOM->getElementsByTagName('*');
//get the text, split it and replace, but keep track of replaced words
$replaced = array();
for ($i = 0, $j = $nodes->length; $i<$j;$i++)
{
$words = explode(' ',$nodes->item($i)->nodeValue);
while($word = array_shift($words))
{
if (!array_key_exists($word, $replaced))
{//avoid replacing twice (and thus creating a link within a link)
$replaced[$word] = true;
$string = str_replace($word, ''.$word.'', $string);
}
}
}
This code is tested and working.

How to get strings sentence by sentence in a html textarea

I have a text area which contains information as follows,
Secured places in the national squad respectively
Selected to the national team this year as well
Selected to the national team twice during his university career
Went to school at ABS
when user click the submit button, I want to get strings in each lines to php variables in submit page, something like this
$a = "Secured places in the national squad respectively";
$b = "Selected to the national team this year as well";
$c = "Selected to the national team twice during his university career";
$d = "Went to school at ABS";
can anyone please tell me how to do this?
If you don't care about sentences but rather line breaks, you should be able to break into an array based on that like this:
$posted_text = $_POST['text']; // or however you get the value into a string
$text_array = explode(PHP_EOL, $posted_text);
I think you looking for
explode('\n\r', $var)
where var is the value your ripping apart
Your best bet would be exploding the string via the newline character \n. Unfortunately, if the user didn't actually hit enter and the text has just rolled onto the next line, there won't be any newline characters to explode by.
Working example wihout breaking lines:
http://codepad.viper-7.com/OBiUXP
$words = explode(" ", str_replace("\n"," ",$text));
$sentences = Array();
$sentence = Array();
foreach($words as $word) {
$word = trim($word);
if(!$word) continue ;
$char1 = substr($word,0,1);
$char2 = substr($word,1,1);
if((strtoupper($char1) == $char1) && (strtolower($char2) == $char2)) {
if(count($sentence)) {
$sentences[] = join(" ", $sentence);
}
$sentence = Array();
}
$sentence[] = $word;
}
if(count($sentence)) {
$sentences[] = join(" ", $sentence);
}

Categories