By clicking “Sign up”, you agree to our terms of service and acknowledge you have read our privacy policy.

Sign up with Google

Sign up with GitHub

OR

Email

Password

Sign up

Already have an account? Log in

Skip to main content

Stack Overflow

About

Products

Stack Internal

Stack Internal
Implement a knowledge platform layer to power your enterprise and AI tools.

Stack Data Licensing
Get access to top-class technical expertise with trusted & attributed content.

Stack Ads
Connect your brand to the world’s most trusted technologist communities.

Releases
Keep up-to-date on features we add to Stack Overflow and Stack Internal.

About the company

Visit the blog

Loading…

Help Center and other resources

Tour

Start here for a quick overview of the site

Help Center

Detailed answers to any questions you might have

Meta

Discuss the workings and policies of this site

About Us

Learn more about Stack Overflow the company, and our products

A list of all 184 Stack Overflow communities

current community

Stack Overflow

Stack Overflow

help
chat

Meta Stack Overflow

Meta Stack Overflow

your communities

Sign up or log in to customize your list.

More communities

company blog

Click to show search

Log in

Sign up

Let's set up your homepage Select a few topics you're interested in:

pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker

Or search from our full list:

javascript

python

java

c#

php

android

html

jquery

c++

css

ios

sql

mysql

r

reactjs

node.js

arrays

c

asp.net

json

python-3.x

.net

ruby-on-rails

sql-server

swift

django

angular

objective-c

pandas

excel

angularjs

regex

typescript

ruby

linux

ajax

iphone

vba

xml

laravel

spring

asp.net-mvc

database

wordpress

string

postgresql

flutter

mongodb

wpf

windows

xcode

amazon-web-services

bash

git

oracle-database

spring-boot

dataframe

azure

firebase

list

multithreading

vb.net

docker

react-native

eclipse

algorithm

powershell

macos

visual-studio

numpy

image

forms

scala

function

vue.js

performance

twitter-bootstrap

selenium

winforms

kotlin

loops

sqlite

hibernate

express

dart

matlab

python-2.7

shell

rest

entity-framework

apache

csv

android-studio

maven

linq

qt

dictionary

unit-testing

asp.net-core

facebook

apache-spark

tensorflow

file

swing

class

sorting

date

unity-game-engine

authentication

go

symfony

t-sql

matplotlib

opencv

.htaccess

google-chrome

for-loop

datetime

codeigniter

perl

http

validation

sockets

google-maps

object

uitableview

xaml

oop

if-statement

cordova

visual-studio-code

ubuntu

web-services

email

android-layout

spring-mvc

elasticsearch

github

ms-access

kubernetes

ggplot2

parsing

selenium-webdriver

user-interface

pointers

c++11

security

google-sheets

ruby-on-rails-3

templates

machine-learning

google-apps-script

flask

nginx

variables

exception

sql-server-2008

gradle

debugging

tkinter

delphi

listview

jpa

asynchronous

haskell

web-scraping

jsp

pdf

ssl

amazon-s3

xamarin

wcf

jenkins

testing

generics

batch-file

google-cloud-platform

npm

ionic-framework

unix

network-programming

recursion

google-app-engine

mongoose

visual-studio-2010

.net-core

android-fragments

assembly

animation

math

svg

session

hadoop

intellij-idea

rust

join

winapi

curl

django-models

laravel-5

heroku

url

http-redirect

inheritance

tomcat

google-cloud-firestore

webpack

gcc

asp.net-mvc-4

image-processing

keras

swiftui

dom

logging

next.js

matrix

actionscript-3

pyspark

button

post

firebase-realtime-database

optimization

cocoa

jquery-ui

xpath

iis

d3.js

xslt

javafx

firefox

internet-explorer

select

caching

asp.net-mvc-3

web

opengl

events

asp.net-web-api

plot

dplyr

magento

stored-procedures

encryption

search

ruby-on-rails-4

amazon-ec2

memory

multidimensional-array

canvas

audio

random

jsf

vector

redux

cookies

input

facebook-graph-api

flash

xamarin.forms

indexing

ipad

arraylist

cocoa-touch

data-structures

video

model-view-controller

serialization

azure-devops

jdbc

awk

razor

apache-kafka

routes

mod-rewrite

servlets

woocommerce

beautifulsoup

filter

excel-formula

iframe

docker-compose

design-patterns

aws-lambda

text

visual-c++

django-rest-framework

cakephp

android-intent

mobile

struct

react-hooks

methods

groovy

mvvm

lambda

ssh

ecmascript-6

checkbox

time

grails

installation

google-chrome-extension

shiny

sharepoint

cmake

jakarta-ee

plsql

android-recyclerview

core-data

spring-security

types

meteor

sed

android-activity

bootstrap-4

activerecord

replace

graph

group-by

vim

scikit-learn

websocket

file-upload

boost

junit

memory-management

sass

async-await

import

eloquent

error-handling

dynamic

deep-learning

silverlight

dependency-injection

soap

apache-spark-sql

layout

charts

svn

gridview

browser

while-loop

deployment

vuejs2

highcharts

google-bigquery

dll

view

ffmpeg

foreach

makefile

c#-4.0

redis

reporting-services

plugins

unicode

reflection

merge

jupyter-notebook

google-maps-api-3

https

twitter

extjs

server

split

oauth-2.0

terminal

axios

cmd

encoding

pip

django-views

collections

database-design

hash

ember.js

netbeans

data-binding

pytorch

apache-flex

tcp

pdo

build

sqlalchemy

concurrency

automation

entity-framework-core

command-line

spring-data-jpa

printing

java-8

react-redux

html-table

neo4j

service

lua

ansible

jestjs

enums

parameters

promise

visual-studio-2012

flexbox

module

material-ui

outlook

uwp

jquery-mobile

web-applications

webview

utf-8

firebase-authentication

mysqli

datatable

python-requests

parallel-processing

colors

drop-down-menu

scipy

tfs

scroll

hive

count

syntax

ms-word

twitter-bootstrap-3

rxjs

ssis

constructor

fonts

file-io

google-analytics

paypal

three.js

cassandra

graphql

gwt

graphics

discord

compiler-errors

react-router

backbone.js

powerbi

socket.io

solr

url-rewriting

memory-leaks

datatables

datagridview

zend-framework

drupal

oauth

nlp

oracle11g

knockout.js

terraform

triggers

interface

django-forms

casting

angular-material

jmeter

neural-network

linked-list

google-api

timer

django-templates

path

windows-phone-7

parse-platform

orm

visual-studio-2015

directory

cron

conditional-statements

arduino

proxy

functional-programming

push-notification

primefaces

pagination

model

jar

xamarin.android

uiview

hyperlink

visual-studio-2013

vbscript

azure-active-directory

google-cloud-functions

swift3

sql-server-2005

download

gitlab

rspec

jwt

process

properties

callback

configuration

combobox

windows-phone-8

pygame

scrapy

linux-kernel

emacs

safari

clojure

x86

permissions

scripting

io

scope

nhibernate

azure-functions

raspberry-pi

mongodb-query

compilation

angularjs-directive

responsive-design

binding

reference

playframework

request

architecture

bluetooth

version-control

doctrine-orm

pyqt

discord.js

dns

3d

f#

rubygems

sql-server-2012

get

package

tree

autocomplete

kendo-ui

datepicker

expo

jackson

yii

openssl

controller

grep

xamarin.ios

nested

static

null

transactions

datagrid

uiviewcontroller

active-directory

statistics

webforms

sas

dockerfile

discord.py

notifications

duplicates

mocking

nullpointerexception

youtube

computer-vision

yaml

pycharm

menu

phpmyadmin

sum

bitmap

plotly

visual-studio-2008

asp.net-mvc-5

blazor

floating-point

yii2

stl

android-listview

css-selectors

jsf-2

time-series

ant

hashmap

character-encoding

msbuild

electron

asp.net-core-mvc

stream

cryptography

google-drive-api

jboss

sdk

joomla

devise

selenium-chromedriver

navigation

background

multiprocessing

binary

anaconda

cuda

iterator

linq-to-sql

pyqt5

camera

cors

onclick

ios7

mariadb

frontend

android-asynctask

microsoft-graph-api

laravel-4

tabs

uicollectionview

rabbitmq

amazon-dynamodb

insert

android-jetpack-compose

linker

environment-variables

coldfusion

xsd

console

textview

upload

continuous-integration

ftp

opengl-es

localization

mockito

json.net

xml-parsing

macros

formatting

type-conversion

data.table

operating-system

timestamp

kivy

integer

calendar

segmentation-fault

vuejs3

android-ndk

prolog

char

jasmine

drag-and-drop

geometry

crash

sprite-kit

automated-tests

dependencies

fortran

azure-pipelines

mfc

android-gradle-plugin

itext

attributes

header

nosql

format

nuxt.js

firebase-cloud-messaging

jquery-plugins

db2

event-handling

julia

odoo

flutter-layout

jenkins-pipeline

annotations

leaflet

keyboard

textbox

visual-studio-2017

arm

gulp

libgdx

timezone

postman

nestjs

stripe-payments

synchronization

azure-web-app-service

dom-events

uikit

aggregation-framework

uiscrollview

namespaces

wso2

crystal-reports

jvm

google-sheets-formula

swagger

sequelize.js

android-emulator

com

chart.js

xampp

subprocess

garbage-collection

webdriver

html5-canvas

geolocation

sql-update

snowflake-cloud-data-platform

dialog

centos

concatenation

numbers

qml

java-stream

widget

set

tuples

ionic2

mapreduce

android-edittext

rotation

nuget

spring-data

doctrine

windows-10

modal-dialog

radio-button

smtp

http-headers

lucene

sonarqube

grid

xmlhttprequest

listbox

switch-statement

initialization

internationalization

boolean

components

ios5

apache-camel

gdb

return

google-play

serial-port

ldap

eclipse-plugin

pivot

youtube-api

latex

frameworks

tags

subquery

c++17

asp-classic

foreign-keys

uinavigationcontroller

containers

delegates

label

dataset

protractor

struts2

copy

uibutton

sql-server-2008-r2

google-cloud-storage

find

embedded

base64

queue

github-actions

migration

arguments

jaxb

append

composer-php

zip

stack

autolayout

cucumber

entity-framework-6

ide

iteration

popup

windows-7

vb6

r-markdown

jqgrid

hover

clang

g++

range

android-viewpager

ssl-certificate

gmail

passwords

Next You’ll be prompted to create an account to view your personalized homepage.

Home

Questions

AI Assist

Tags

Stack Overflow for Agents

Challenges

Chat

Articles

Users

Companies

Collectives

Communities for your favorite technologies. Explore all Collectives

Stack Internal

Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.

Try for free
Learn more

Stack Internal

Bring the best of human thought and AI automation together at your work.
Learn more

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Stack Internal

Knowledge at work

Bring the best of human thought and AI automation together at your work.

Explore Stack Internal

PHP: Prepend/append string to a variable

Ask Question

Asked
10 years, 4 months ago

Modified
10 years, 4 months ago

Viewed
1k times

Part
of PHP Collective

Report this ad

This question shows research effort; it is useful and clear

0

This question does not show any research effort; it is unclear or not useful

Save this question.

Show activity on this post.

so I have been trying to wrap my head around this thing few hours,
but nothing seems to work as expected.

Copy
for($i = 0 ; $i < count($lines); $i++){
$currentLine = $lines[$i];
$search = array('ø', '', 'ï', 'ò');$replace = array('ř', 'ť', 'ď', 'ň');
$subject = str_replace($search, $replace, $currentLine);
$finalLine = '"'.$subject.'",';
file_put_contents($fileName, $finalLine, FILE_APPEND);
};

The thing is simple, I am iterating over lines in .dic file (it's just list of words, one word at a line),
for each word I do some replacing of wrong characters and at the end of all I try to wrap the word in double quotes (single quotes don't work either).

The problem is, that the quotes aren't added correctly, and instead of "someword", i get ","someword

Copy
// $currentLine = someword;
echo '"'.$currentLine.'",';

// returns
","someword

I need this to convert .dic file to json so i can use it in javascript game i am making.

Can someone please help? I can't find any similar question, not here, not on google, nothing. I tried single quotes, i tried making the whole thing array

Copy
$newline = Array(
0 => '"',
1 => $currentLine,
2 => '",'
)

and then joining the array but with the same result, I am kinda desperate now, so if someone knows what am I doing wrong, please tell me.

PHP Collective

php

string

append

Share

Share a link to this question

Copy linkCC BY-SA 3.0

Short permalink to this question

Improve this question

Follow

Follow this question to receive notifications

edited Mar 27, 2016 at 16:55

asked Mar 27, 2016 at 16:21

Vincurekf

10733 silver badges99 bronze badges

6

1

This should work, you concatenate the line between quotes, so the output should also be between quotes

Rizier123

–
Rizier123

2016-03-27 16:24:38 +00:00

Commented
Mar 27, 2016 at 16:24

And for json - there's json_encode and not the wheels, you're inventing here.

u_mulder

–
u_mulder

2016-03-27 16:25:35 +00:00

Commented
Mar 27, 2016 at 16:25

1

It might be your intent, but you do know that you are appending to ` $finalLine` and then also appending $finalLine to the $fileName file after every loop iteration?

Chris

–
Chris

2016-03-27 16:26:55 +00:00

Commented
Mar 27, 2016 at 16:26

@Chris oh my bad, I must have left that there from another unsuccessful try.

Vincurekf

–
Vincurekf

2016-03-27 16:54:28 +00:00

Commented
Mar 27, 2016 at 16:54

Are you appending one line at a time because the .dlc file is very large?

Greg

–
Greg

2016-03-27 16:56:38 +00:00

Commented
Mar 27, 2016 at 16:56

|

Show 1 more comment

1 Answer 1

Sorted by:

Reset to default

Highest score (default)

Trending (recent votes count more)

Date modified (newest first)

Date created (oldest first)

This answer is useful

1

This answer is not useful

Save this answer.

Loading when this answer was accepted…

Show activity on this post.

I can't tell from the code why you are getting that result. But here is an alternative approach that might help.

Copy
// Set these outside the loop
$search = array('ø', '', 'ï', 'ò');
$replace = array('ř', 'ť', 'ď', 'ň');

$subjects = array();

foreach ($lines as $line)
{
$subject = str_replace($search, $replace, $line);
$subject = trim($subject); // trim if you want to remove extraneous spaces

if (!empty($subject)) // Presumably you don't want to add empty lines if there are any
{
$subjects[] = $subject;
}
}

$allwords = implode(',', $subjects);

file_put_contents($fileName, $allwords, FILE_APPEND);

Essentially, create an array of the words, join them with "," using the implode() library function and then add the whole lot to your file.

Share

Share a link to this answer

Copy linkCC BY-SA 3.0

Short permalink to this answer

Improve this answer

Follow

Follow this answer to receive notifications

answered Mar 27, 2016 at 17:09

Greg

2,59344 gold badges2222 silver badges2727 bronze badges

2 Comments

Add a comment

Vincurekf

Vincurekf Over a year ago

Yes that works, but still, i need those words in quotes, because there are some words like "key" "default" "break" and so on, and when i import this file into javascript, it breaks on those words. But thanks, this is still better than what I did. Update: Got it joined with '","', now i just need to add the stating and ending quote. Thanks @Greg.
2016-03-27T18:43:14.17Z+00:00

0

Reply

Copy link

Greg

Greg Over a year ago

Sorry, I forgot about the quotes but great that you got them added.
2016-03-27T19:52:48.137Z+00:00

0

Reply

Copy link

Your Answer

Reminder: Answers generated by AI tools are not allowed due to Stack Overflow's artificial intelligence policy

Thanks for contributing an answer to Stack Overflow!

Please be sure to answer the question. Provide details and share your research!

But avoid …

Asking for help, clarification, or responding to other answers.

Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved

Draft discarded

Sign up or log in

Sign up using Google

Sign up using Email and Password

Submit

Post as a guest

Name

Email

Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

php

string

append

See similar questions with these tags.

PHP
Collective

See more

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Try Stack Overflow for Agents

Verified knowledge for the agentic era

Paste this into your AI coding assistant:

Help me join Stack Overflow for Agents here. Read https://agents.stackoverflow.com/skill.md, then start onboarding.

Copy onboarding snippet

Supports Claude Code, Cursor, Codex, Windsurf and more.

Explore Stack Overflow for Agents

The Overflow Blog

Building an agentic SDLC with a QA engineering mindset

Featured on Meta

How we talk about ourselves (and to you)

Policy: Generative AI (e.g., ChatGPT) is banned

Are the existing open-ended question tags enough to define the scope of...

Report this ad

Report this ad

Community activity

Last 1 hr

Users online activity

4083 users online

3 questions

3 answers

41 comments

147 upvotes

Popular tags

c++flutteradvicepythonc#android

Popular unanswered question

COCO dataset: get different image id with 2 approaches

pythoncomputer-visionobject-detectionyolo

Rahn

5.6k

2,228 days ago

Related

7604

What is the difference between String and string in C#?

7402

How to check whether a string contains a substring in JavaScript?

5518

How do I replace all occurrences of a string?

5414

How do I make the first letter of a string uppercase in JavaScript?

2889

How to append something to an array?

3522

How can I assign a multiline string literal to a variable?

5139

Reference Guide: What does this symbol mean in PHP? (PHP Syntax)

2883

Check if a variable is a string in JavaScript

3109

What is the difference between Python's list methods append and extend?

4771

How do I read / convert an InputStream into a String in Java?

Hot Network Questions

Equalizing numbers on a circle by averaging adjacent pairs

How to use visualcounter with r2l text?

Is there a list of "well-known" vsock ports?

Does anyone know what MLI looks like after it has vented?

MySQL : Linking a cell to another cell in the same table

How can I know the safe repetitive peak current of a rectifier diode without an IFRM rating?

Conflict with `luatexja` and `\DocumentMetadata{tagging=on}`?

Short story about dolphin-to-human brain transplants

Connection from night train to regional train in Romania

Using package poetry, no list of poems created

How to create a dynamic fan in TikZ in LaTeX?

Loss of water pressure downstairs suddenly. What problem solving steps do I need?

What does Judaism say about voting in Mi Yodeya moderator elections?

Exporting multiple Geometry Nodes instances as 2D SVG lines

How can I add a "View contact record" link to Drupal user pages again?

Is "suggest one's doing something" acceptable?

How does Resistance stack with Half-Damage Effects?

Responding to technical queries from Master students from old employers/labs

Is custom an acceptable reason to remove an agreed upon author from a publication?

Was Shimon Hatzadik the only P'rushi left in Anshei K'nesses Hagdola?

Should I meet with a professor to discuss joining his lab if I am leaving soon?

"Don’t tell anyone he has died" - source?

в очень with a glottal stop

Steam game kind of like Jet Set Radio, involves combating an authoritarian government by skating/parkouring protagonists, one of which may be a robot

Question feed

Subscribe to RSS

Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-php

Why are you flagging this comment?

Probable spam.
This comment promotes a product, service or website while failing to disclose the author's affiliation.

Unfriendly or contains harassment/bigotry/abuse.
This comment is unkind, insulting or attacks another person or group. Learn more in our Abusive behavior policy.

Not needed.
This comment is not relevant to the post.

Enter at least 6 characters

Something else.
A problem not listed above. Try to be as specific as possible.

Enter at least 6 characters

Flag comment Cancel
You have 0 flags left today

Hang on, you can't upvote just yet.

You'll need to complete a few actions and gain 15 reputation points
before being able to upvote. Upvoting indicates when questions and answers are useful. What's reputation and how do I get it?

Instead, you can save this post to reference later.

Save this post for later Not now

Stack Overflow

Questions

Help

Chat

Business

Stack Internal

Stack Data Licensing

Stack Ads

Company

About

Press

Work Here

Legal

Privacy Policy

Terms of Service

Contact Us

Your Privacy Choices

Cookie Policy

Stack Overflow’s open communities

Technology

Culture & recreation

Life & arts

Science

Professional

Business

API

Data

Blog

Facebook

Twitter

LinkedIn

Instagram

Site design / logo © 2026 Stack Exchange Inc;
user contributions licensed under
CC BY-SA
.
rev 2026.8.19.45145

By continuing to use this website, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. By exiting this window, default cookies will be accepted. To reject cookies, select an option from below.

Necessary cookies only
Customize settings

Report this ad